apache - 重写 url - apache - htaccess
问题描述
我正在将现有网站迁移到 Codeigniter 网站,因此需要帮助重新编写 url。
我需要将旧 URL 与新 URL 映射,以便从搜索引擎结果访问站点的人被重定向到匹配的新 URL,否则他们会得到页面未找到错误。
这种格式的大多数旧网址,例如
/page.php?id=5 or /page.php?id=180&t=78
/data.php?token=GH45LK
/faqs.php?k=98#section2
他们匹配的新网址是
/page/5 or I will be happy with /page?id=5&whatever=xyz too
/data/GH45LK
/faqs/98#section2
这是我当前的 CodeIgniter 的 .htaccess
# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
RewriteBase /
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
RewriteBase /
我在行后尝试了这样的事情
RewriteRule ^data\.php\?token=(.*)?$ data/=$1 [R=301,L]
但不确定我是否正确,因为它不起作用。
你能帮我把它弄对吗?谢谢
解决方案
RewriteRule
不是这样工作的:它只测试 URL 的路径部分。对于所有其他部分(域,查询字符串,...),您需要使用RewriteCond
和相应的变量(%{QUERY_STRING}
,用于查询字符串/此处)。
RewriteCond %{QUERY_STRING} (?:^|&)id=(\d+)
RewriteRule ^page\.php$ /page/%1 [L,R=permanent]
RewriteCond %{QUERY_STRING} (?:^|&)token=([^&]+)
RewriteRule ^data\.php$ /data/%1? [L,R=permanent]
RewriteCond %{QUERY_STRING} (?:^|&)k=(\d+)
RewriteRule ^faqs\.php$ /faqs/%1? [L,R=permanent]
RewriteCond %{HTTPS} !=on
而且我认为当您重定向时存在错误http://
,而不是https://
,这应该导致无限循环。
另请注意,锚(在您的示例中为#section2)不会发送到服务器(因此无法重写)。
推荐阅读
- python - Python 在日志记录中向基于 structlog 的格式化程序添加额外字段
- elasticsearch - elasticsearch中如何正确翻转索引
- python - jupyter lab 上未显示的绘图和小部件
- powershell - 要求用户填充字段(Powershell)
- layout - qiskit 的转译器中的 DenseLayout 是如何工作的?
- android - 我无法解决此错误 [android]
- laravel - Laravel vue:我无法获取与模型之间的关系相关的对象
- amazon-web-services - 如果我在 AWS 组织中创建 AWS 账户,我可以从拥有该组织的根账户中删除它吗?
- mysql - 获取 id 最高的行
- c# - Xamarin - 应用程序外部的浮动按钮