【发布时间】:2020-08-12 09:59:33
【问题描述】:
我正在尝试创建一个简单的 htaccess 脚本,它将用户重定向到相应的页面。因此,例如,如果文件/文件夹不存在,则导航到 /listing/id 的用户将显示为 listing.php?id=id,或者如果他们导航到 /username,则将显示为 profile.php?id=username。
问题是,当访问/listing/id 时,我检索到一个内部服务器错误。但不是因为处理这部分的RewriteRule - 而是因为我的 htaccess 脚本的.php 扩展删除部分(我在注释掉它时发现了这一点)。我不知道为什么这不起作用,因为我相信我设置了正确的标志,并且正在使用正确的代码块。
我的代码
Options +FollowSymLinks -Indexes -MultiViews
RewriteEngine On
# no php extension
# (/listing/id will work if this is commented out, but the other pages won't without the .php extension)
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
# redirect to www.*
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com [R=301,L]
# only allow rewriting to paths that don't exist
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+) - [PT,L]
# external profile.php?id=$id to /$id
RewriteCond %{THE_REQUEST} /profile\.php\?id=([\w-]+) [NC]
RewriteRule ^ /%1? [R=301,L]
# /listing/$id
RewriteRule ^listing/([\w-]+)/?$ listing.php?id=$1 [L,QSA,NC]
# /$username
RewriteRule ^([\w-]+)/?$ profile.php?id=$1 [L,QSA]
示例案例
-
/(索引)工作 -
/searchworks(该文件存在,因此它重定向到搜索页面而不是名为 search 的用户) -
/usernameworks(username.php 不存在,因此重定向到个人资料页面) -
/listing/test返回Internal Server Error 500(删除我的 htacess 的 no PHP extension 部分会导致此页面正常工作,但现在所有其他页面都需要附加.php)
感谢所有帮助,干杯。
【问题讨论】:
标签: regex apache .htaccess mod-rewrite