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

时间:2021-11-02 08:17:18

Previously my website had URLs for countries; for example: www.abc.com/uk, www.abc.com/us, www.abc.com/cn.

以前我的网站有国家/地区的网址;例如:www.abc.com/uk,www.abc.com / us,www.abc.com / cn。

But now my URL structure has changed to a longer form. For example: www.abc.com/united-kingdom, www.abc.com/united-states, www.abc.com/china.

但现在我的URL结构已更改为更长的形式。例如:www.abc.com/united-kingdom,www.abc.com/united-states,www.abc.com/china。

How can I set RewriteRule in .htaccess so that the old URL will redirect to the new one?

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

2 个解决方案

#1


Try this code in your /.htaccess file :

在/.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]

#2


RewriteMap is an excellent solution for this:

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]

Then in your path/to/countrymap.txt:

然后在你的路径/ to / countrymap.txt中:

uk united-kingdom
us united-states
cn china

If you want to replace http://www.example.com/uk/something with http://www.example.com/united-kingdom/something, then use the following rule instead:

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

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

To make your redirect permanent, change R to R=301.

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

#1


Try this code in your /.htaccess file :

在/.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]

#2


RewriteMap is an excellent solution for this:

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]

Then in your path/to/countrymap.txt:

然后在你的路径/ to / countrymap.txt中:

uk united-kingdom
us united-states
cn china

If you want to replace http://www.example.com/uk/something with http://www.example.com/united-kingdom/something, then use the following rule instead:

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

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

To make your redirect permanent, change R to R=301.

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