如何为带有GET参数的URL创建重写规则?

时间:2019-02-01 14:35:56

标签: regex .htaccess mod-rewrite url-rewriting

我正在尝试重写这种类型的URL:

http://www.example.com/news/?lang=en

http://www.example.com/en-news

这也应该是递归的,这意味着:

http://www.example.com/news/world/?lang=en

应重写为:

http://www.example.com/en-news/en-world/

到目前为止,我的.htaccess文件中已有此文件(已使用arkasha的answer进行了修改):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# Rewrite language parameter
RewriteCond %{QUERY_STRING} (^|&)lang=(\w+)
RewriteRule /?(\w+)/?$ %1-$1 [END]
</IfModule>

但这似乎不起作用。

1 个答案:

答案 0 :(得分:1)

您需要使用重写条件从查询字符串中捕获令牌,然后才能在重写规则中使用它:

RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)lang=(\w+)
RewriteRule /?(\w+)/?$ %1-$1 [END]

该规则集应在http服务器主机配置或动态配置文件(“ .htaccess”样式文件)中同样起作用,但是,您应该优先选择第一个选项。显然,重写模块需要加载到http服务器中并在http主机内部启用。如果决定使用动态配置文件,则还需要确保完全启用了它的解释功能,并且它位于正确的位置。

相关问题