URL Rewrite(.htaccess) index.php?page=foo&lang=en to /en/foo



我是使用.htaccess重写URL的新手,我正在努力使用它。

我想要的是更改与此类似的urlhttp://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]
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]

解释

区块1

不使用https或使用www.处理所有请求

http://www.example.org/whatever=>https://example.org/whatever

区块2

处理根/请求并添加en作为默认语言

https://example.org/=>https://example.org/en

区块3

处理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

这里有一个符合您需求的.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?

将以下URL重定向到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?

将以下URL重定向到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

用其他值更改contacten以查看的变化

以下是的实时示例

最新更新