多重重写规则导致服务器内部错误


Multible RewriteRules result in Internal Server Error

强迫这个工作让我有点疯狂,所以我希望你能帮助我。

我使用重写规则和。htaccess来创建我的动态URL

example.com/page.php?id=1 

看起来像这样

example.com/1
使用

RewriteRule    ^([A-Za-z0-9-]+)/?$    page.php?id=$1    [NC,L] 

,到目前为止它运行得很好。
但我也想隐藏的文件类型在URL (impressum.phpimpressum)使用

RewriteRule (.*) $1.php [L]

所以两个规则都工作完全正确,只要我不同时使用它们。当我这样做时,它看起来像这样(我的完整文件)

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) $1.php [L]
RewriteRule ^([A-Za-z0-9-]+)/?$    page.php?id=$1    [NC,L] 

,我得到一个内部服务器错误。我尝试了不同的版本,例如改变位置等,但我总是得到这个错误。

所以我的问题是:我如何得到两个规则在一起和工作,而URL结束仍然隐藏和example.com/1工作太?

非常感谢您的回答

您可以在.htaccess文件中使用以下内容:

RewriteEngine on
# Check if the PHP file exists and route accordingly
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]
# If not, pass the request to page.php if it contains A-Za-z0-9-
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z0-9-]+)/?$    page.php?id=$1    [NC,L] 

您需要两个单独的规则。重写条件将只应用于紧跟其后的规则,对于php扩展规则,您必须在将php添加到末尾之前检查php文件是否存在:

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([A-Za-z0-9-]+)/?$    page.php?id=$1    [NC,L]