重写规则以隐藏扩展名.htaccess



我正试图从链接中隐藏.php文件的扩展名

例如www.example.com/about.php显示www.example.com/about

我做了什么

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L] 

而且效果非常好。

但我有另一个链接example.com/news.php?id=45根据上面的规则,我可以访问类似的链接

example.com/news?id=45 without .php

但我想隐藏id=45我想像这个example.com/news/45一样

我做了什么RewriteRule ^news.php?id=([0-9]+) /news/$1 [NC,L]

但它不起作用我得到500内部服务器错误

改为这样尝试:

# MultiViews must be disabled for "/news/45" to work
Options -MultiViews
RewriteEngine on
# Rewrite "/news/45" to "news.php?id=45"
RewriteRule ^news/(d+)$ news.php?id=$1 [L]
# Handle extensionless ".php" URLs
RewriteCond %{REQUEST_URI} !.w{2,3}$
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

您的500内部服务器错误实际上是由您的原始指令";隐藏";.php扩展,而不是您的";新的";指令(实际上什么都没做(。您的原始指令会将/news/45/news/45.php/news/45.php.php等的请求重写,从而创建重写循环(500错误(。

有关此行为的详细解释,请参阅我对ServerFault上以下问题的回答:https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error

我做了什么RewriteRule ^news.php?id=([0-9]+) /news/$1 [NC,L]

但它不起作用我得到500内部服务器错误

此指令的逻辑被颠倒,并且永远不会真正匹配请求的URL(或者任何东西(,因此实际上不会执行的任何事情。然而,它在语法上是可以的,所以不会触发错误。

500错误可能只是通过请求/news/45(使用原始指令(发生的,无论该指令是否到位。

最新更新