简体   繁体   中英

mod_rewrite all domains to one tld

I'm looking for a way to transparently (without redirect) rewrite all domains to the same domain but one tld. So:

random.domain.tld -> random.domain.local

where there is an unknown number of segments before the tld, the tld itself is unknown, and the tld will never have dots in it (like co.uk) so it should be simply everything before the last do and everything after the last dot.

I've tinkered around with this for a while with no luck:

RewriteRule ^([^.]+)\.([^\.]*?)$ $1.local [L]

You cannot do that with a simple RewriteRule, since that only works on the path of a url. Instead you require a RewriteCond to get an additional reference:

RewriteEngine on
RewriteCond %{HTTP_HOST} !\.local$
RewriteCond %{HTTP_HOST} ^(.+)\.[^.]+$
RewriteRule ^(.*)$ http://%1.local$1 [P,QSA]

A general hint for such rewriting rules: if you have access over the http server configuration then you should always prefer to put such rules into the host configuration section. .htaccess style files are notoriously error prone, they make things complex, are hard to debug and slow the server down. They are only an alternative, if you do not have access to the http server configuration.

If however the goal simply is to have a temporary way to "redirect" request for testing purposes, then often the easier and more elegant way is to make local DNS entries overriding the real addresses of the domains to be tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM