regex - 如何使用 mod_rewrite 从旧的 php 脚本重定向到新的 php 脚本

标签 regex apache .htaccess mod-rewrite seo

这是我的第一个请求,希望我不会让任何人不高兴。

这是我的故事:

我找遍了这个地方寻找解决方案,但没能找到。希望有人能提供一些意见。

我基本上已经设法使用 Apache 的 mod_rewrite 为我的网站创建 SEO 友好的 url。

例如旧路径 www.hostname/index1.php?session=user 现在被重写为 www.hostname/user,这将生成一个 SEO 友好的 URL 地址。

但是,旧路径仍然有效。我需要以某种方式将所有传入的旧 index1.php 请求重定向到较新的 URL,即 SEO 友好的 URL,以便搜索引擎将链接流行度转移到新的 URL。我相信我可能有一个无限循环重定向,这就是它不起作用的原因。

到目前为止我的代码:

Options +FollowSymLinks
RewriteEngine On
RewriteBase / 

## Redirect still valid old links to SEO friendly ones
RewriteRule ^/?index1\.php\?session=user$ /user [R=301]

## Catch the above and rewrite the URL 
RewriteRule ^/?user/?$ /index1.php?session=user [QSA,L]

在解析 htaccess 文件时,上述规则永远不会命中

我突然想到我可能在这里做某种重定向循环,所以我考虑将 index1.php 文件重命名为 index2.php 并创建如下内容:

## Redirect still valid old links to SEO friendly ones
RewriteRule ^/?index1\.php\?session=user$ /user [R=301]

## Catch the above and rewrite the URL 
RewriteRule ^/?user/?$ /index2.php?session=user [QSA,L]

然而,那也失败了。

最好的方法是什么?我在这里做错了什么?

谢谢!

最佳答案

将您的 .htaccess 规则更新为

Options +FollowSymLinks
RewriteEngine On
RewriteBase / 

## Redirect still valid old links to SEO friendly ones
RewriteCond %{QUERY_STRING} !no-redir [NC]
RewriteCond %{QUERY_STRING} session=user [NC]
RewriteRule ^/?index1\.php$ /user? [R=301,NC,L]

## Catch the above and rewrite the URL 
RewriteRule ^/?user/?$ /index1.php?session=user&no-redir [QSA,NC,L]

关于regex - 如何使用 mod_rewrite 从旧的 php 脚本重定向到新的 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334882/

相关文章:

php - Htaccess 不适用于 Mamp

python - htaccess 导致 python cgi 出现问题

.htaccess - Wordpress Multisite .htaccess ..请解释功能

c# - 用于匹配倒数第二个反斜杠后所有内容的正则表达式

没有等号的 C++ Regex Alpha

PHP代码没有被执行,但是代码显示在浏览器源代码中

WordPress在插件开发中添加重写规则和条件

regex - 重定向除图像以外的所有内容

javascript - 没有什么可重复的 Javascript 正则表达式

python - 目标 WSGI 脚本 '/opt/python/current/app/.../wsgi.py' 无法作为 Python 模块加载