[英]URL Rewriting(.htaccess) index.php?page=foo&lang=en to /en/foo
我是使用 .htaccess 进行 URL 重写的新手,我正在努力解决它。
我想要的是更改类似于此http://www.example.org/index.php?page=contact&lang=en(lang有 3 个选项,而页面值根据当前页面而变化)的网址,例如 -到https://example.org/en/contact - 非 www 和 https 版本)。
此外,如果有人访问https://example.org/,我想将他们重定向到https://example.org/en (默认)
到目前为止,这是我在 .htaccess 中所拥有的,它不能正常工作。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0&lang=$1 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)(&lang=en)?$
RewriteRule ^index\.php$ /%1? [R=301,L]
这是一个符合您需求的.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteRule (.*) https://%{HTTP_HOST}/en?
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteCond %{QUERY_STRING} page=(\w+)&lang=(\w+)
RewriteRule (.*) https://%{HTTP_HOST}/%1/%2?
解释
第一个条件和规则
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteRule (.*) https://%{HTTP_HOST}/en?
将以下网址重定向到http://www.example.org/en
http://www.example.org
http://www.example.org/
http://www.example.org/index.php
第二个条件和规则
RewriteCond %{REQUEST_URI} ^(\/index\.php)?
RewriteCond %{QUERY_STRING} page=(\w+)&lang=(\w+)
RewriteRule (.*) https://%{HTTP_HOST}/%1/%2?
将以下网址重定向到http://www.example.org/contact/en `
http://www.example.org/index.php?page=contact&lang=en
http://www.example.org/?page=contact&lang=en
http://www.example.org?page=contact&lang=en
使用其他值更改contact
和en
以查看更改
这是一个实时示例
RewriteEngine On
#1
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
#2
RewriteRule ^/?$ https://%{HTTP_HOST}/en? [R=301,L]
#3
RewriteCond %{REQUEST_URI} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)&lang=(\w+)$
RewriteRule "(.*)" "https://%{HTTP_HOST}/%2/%1?" [R=301,L]
处理所有不带 https 或带 www 的请求。
http://www.example.org/whatever => https://example.org/whatever
处理 root /
请求并将en
添加为默认语言
https://example.org/ => https://example.org/en
处理 index.php?page=x&lang=x 请求并用路径段替换查询参数
https://example.org/index.php?page=contact&lang=en => https://example.org/en/contact
所有 3 个一起应满足您描述的要求
http://www.example.org/index.php?page=contact&lang=en => https://example.org/en/contact
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.