php - 我想使用 .htaccess 从 url 中删除问号和 .php 扩展名

标签 php .htaccess

我对 .htaccess 中的重定向 URL 有疑问。我想从 URL 中删除 .php 和问号。

例如:www.example.com/test.php?id=12www.example.com/test/12需要这样的格式。

我尝试在我的 .htaccess 中使用这段代码

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

此代码只是从 URL 中删除了 .php 扩展名。还需要去掉问号。

最佳答案

该代码似乎来 self 的一个答案:)

用这个替换你的代码:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

## hide .php extension snippet

# To externally redirect /dir/foo.php?id=123 to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\?id=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R,L]

# To internally forward /dir/foo/12 to /dir/foo.php?id=12
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/([^/]+)/?$ $1.php?id=$2 [L,QSA]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L]

关于php - 我想使用 .htaccess 从 url 中删除问号和 .php 扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963051/

相关文章:

php - PHP中有正则表达式优化器吗?

regex - 在单词后用 4 个数字替换 URL 模式

regex - 301 重定向到带有查询字符串的 URL

apache - 重写所有带有 .html 扩展名的 url(index.html 除外)

php - 如何安全地使用 file_get_contents?

php - 从提交数组更新表数据会导致所有行因为相同的数据

树莓派上的 JavaScript

javascript - 如何使用 Ajax 添加更多过滤器和寻呼机

php - htaccess 中的 auto_prepend_file 不适用于子目录

php - 使用 htaccess 文件动态 url 重写