如何在htaccess中设置国家/地区URL RewriteRule

时间:2015-05-08 02:43:03

标签: apache .htaccess mod-rewrite

以前我的网站上有国家/地区的网址;例如:www.abc.com/ukwww.abc.com/uswww.abc.com/cn

但现在我的网址结构已更改为更长的形式。例如:www.abc.com/united-kingdomwww.abc.com/united-stateswww.abc.com/china

如何在.htaccess中设置RewriteRule,以便将旧网址重定向到新网址?

2 个答案:

答案 0 :(得分:0)

在/.htaccess文件中尝试此代码:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^uk/?$ http://www.example.com/united-kingdom [R,L,NC] 
RewriteRule ^us/?$ http://www.example.com/united-states [R,L,NC] 
RewriteRule ^cn/?$ http://www.example.com/china [R,L,NC]

答案 1 :(得分:0)

RewriteMap是一个很好的解决方案:

RewriteEngine on

RewriteMap countrymap "txt:/path/to/countrymap.txt"

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^([a-z]{2})/?$ /${countrymap:$1} [R,NC,L]

然后在path/to/countrymap.txt

uk united-kingdom
us united-states
cn china

如果您想将 http://www.example.com/uk/something 替换为 http://www.example.com/united-kingdom/something ,请改用以下规则:

RewriteRule ^([a-z]{2})/(.*)$ /${countrymap:$1}/$2 [R,NC,L]

要使重定向永久化,请将R更改为R=301