微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我试图在 mod_rewrite 中模拟 else

如何解决我试图在 mod_rewrite 中模拟 else

我有这个代码

RewriteEngine On

# Delete .PHP extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.PHP -f
RewriteRule ^([^.]+)$ $1.PHP [L]

# If file does not exist redirect to error.PHP
RewriteCond %{REQUEST_FILENAME}.PHP !-f
RewriteRule ^(.*)$ error.PHP [L]

# Friendly URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.PHP -f
RewriteRule ^user/(.*)$ user.PHP?ID=$1 [L] 

问题:第二条语句本身有效,但是当我添加第一条语句时,第二条语句总是将我重定向到 error.PHP

可能的解决方案:我想过做这样的事情:

if(RewriteCond %{REQUEST_FILENAME}.PHP !-f)
    RewriteRule ^(.*)$ error.PHP [L]
else
    RewriteRule ^user/(.*)$ user.PHP?ID=$1 [L] 

我已经有一段时间试图自己弄清楚如何让它工作,但我不能。 A 将不胜感激。

解决方法

像这样:

Options -MultiViews
RewriteEngine On

# Friendly URL for user/...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/(.*)$ user.php?ID=$1 [L,QSA,NC] 

# Add .php extension internally
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+?)/?$ $1.php [L]

# If there is no rewrite and 
# files/directory don't exist then forward to error.php
RewriteCond %{ENV:REDIRECT_STATUS} ""
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . error.php [L]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。