How to rewrite URL based on domain in apache and add extra parameter?

爷,独闯天下 提交于 2020-01-06 11:05:15

问题


Basically, what I want to do is to rewrite all urls because we have many different languages. We have a server that hosts several domains. We have www.example.com, www.example.fr, www.example.de, www.anotherdomain.com, www.anotherdomain.de. What I want to do is to redirect all requests from example.xxx to www.example.com with extra url parameter lang=en. This should not affect other domains like www.anotherexample.com etc.

This does not work:

RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.de$
RewriteRule ^(.*)$   http://www.example.com/$1?lang=de [PT]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.fr$
RewriteRule ^(.*)$   http://www.example.com/$1?lang=fr [PT]

One thing that makes it even more difficult is that the ServerName is totally different than the host name, it is called prod.migr.com.

Any suggestions would be appreciated.


回答1:


Try this:

RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.de$
RewriteRule ^  http://www.example.com%{REQUEST_URI}?lang=de [L,R=301,QSA]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.fr$
RewriteRule ^  http://www.example.com%{REQUEST_URI}?lang=fr [L,R=301,QSA]



回答2:


The PT flag is most likely your problem. I've never seen it used when the target is a full domain address because it's meant for URI's to be further redirected with mod_alias.

The flag you should be using is the QSA flag in case the page the user is visiting has a query string on it.

RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.de$
RewriteRule ^(.*)$   http://www.example.com/$1?lang=de [QSA]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.fr$
RewriteRule ^(.*)$   http://www.example.com/$1?lang=fr [QSA]

However, a much better solution would be to check the host the user is visiting in your server-side language such as php or asp if all languages are hosted on the same server like this.

EDIT in response to additional information:

You can not get POST variables through rewriting to different domains like that because it has to redirect the request.

Your best bet is to determine the language in your server side language instead of using mod_rewrite.

If you use php it would be like this

$lang = substr(strrchr($_SERVER['HTTP_HOST'], '.'), 1);

Other languages have similar ways to determine the host.



来源:https://stackoverflow.com/questions/1187117/how-to-rewrite-url-based-on-domain-in-apache-and-add-extra-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!