htaccess中的RewriteRules以提供清晰的URL解析,并从完整URL重定向到清晰的URL

问题描述 投票:0回答:1

我正在研究一个网站项目,www.experimonkey.com。在根目录中,我有使用php动态提供的实验,游戏等目录。我想清理URL,以便例如用户可以转到/experiments?eid=homemade-lava-lamp而不是/experiments/homemade-lava-lamp。我还想进行重定向,以便如果用户转到旧链接/experiments?eid=homemade-lava-lamp,他们将被重定向到干净链接。

我以为我已经用/experiments/.htaccess中的以下代码找出了问题的第一部分:

    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9\-]+)/?$ index.php?eid=$1 [L]

这适用于动态页面;但是,我后来意识到这会破坏/experiments文件夹中的其他实际目录。例如,地址/experiments/submit(实际上是/experiments/submit/index.php)重定向到/experiments/submit?eid=submit-为什么我不知道。

但是,无论我尝试以下代码的任何组合(以及我阅读的所有其他线程和文档),我都无法获取旧的URL来重定向到干净的URL:

    RewriteCond %{QUERY_STRING} eid=(.+)
    RewriteRule .+ https://www.experimonkey.com/experiments/%1 [R=301]

RewriteEngine开

编辑(几乎可以正常工作)

到目前为止,我已经解决了。现在,大多数事情都可以正常工作了,除了最后两个部分创建了一个无限循环,我不确定如何解决它。

#Ignore existing directories and files unless has query string
RewriteCond %{QUERY_STRING} !eid=(.*)
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

#Redirect and remove query string
RewriteCond %{QUERY_STRING} /?eid=(.*)
RewriteRule (.*) https://www.experimonkey.com/experiments/%1? [R=301,L] 

#Rewrite internally to actual URL
RewriteRule ^([a-zA-Z0-9\-]+)/?$ index.php?eid=$1 [L]
apache .htaccess mod-rewrite
1个回答
0
投票

我终于想通了,我希望这可以在途中对某人有所帮助(老实说,我不敢相信这花了我多长时间来弄清楚)。

#Ignore existing directories and files unless has query string
RewriteCond %{QUERY_STRING} !eid=(.*)
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

#Redirect and remove query string. 
#First line was the crucial condition to stop loop by checking for internal redirect first.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} /?eid=(.*)
RewriteRule (.*) https://www.experimonkey.com/experiments/%1? [R=301,L] 

#Rewrite internally to actual URL
RewriteRule ^([a-zA-Z0-9\-]+)/?$ index.php?eid=$1 [L]
© www.soinside.com 2019 - 2024. All rights reserved.