Mod rewrite for fake subdomains?

2020-02-10 10:24发布

I really tried tons of methods but i'm not successful. I want a .Htaccess code to do the following :

I want to rename this : http://www.mydomain.com/media --> http://media.mydomain.com

So, By example instead of calling this : http://www.mydomain.com/media/XXX/picture.jpg i will call : http://media.mydomain.com/XXX/picture.jpg

Thank you

3条回答
The star\"
2楼-- · 2020-02-10 10:50

Make sure rewrite_module is loaded, something like;

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

Then add the following (to your .htaccess):

RewriteEngine on
RewriteCond %{HTTP_HOST} www.mydomain.com
RewriteRule ^/([^/]*)(.*) http://$1.mydomain.com$2 [L,R]

The Cond will only match www.mydomain.com. The Rule then will split the URL into 2 using the first '/' (which will be included in $2), rewrite and redirect.

查看更多
Fickle 薄情
3楼-- · 2020-02-10 11:02

If you want the opposite (see Roger's comment) and without redirecting the user

RewriteEngine on
RewriteCond   %{HTTP_HOST}                 !^www\.mydomain\.com$
RewriteRule   ^(.+)                        %{HTTP_HOST}$1          [C]
RewriteRule   ^([^.]+)\.mydomain\.com(.*)  http://www.mydomain.com/$1$2 [L]

Also, see here: http://httpd.apache.org/docs/1.3/misc/rewriteguide.html

查看更多
欢心
4楼-- · 2020-02-10 11:04

It's gonna be like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(?!www\.)([^.]+)\.mydomain\.com$
RewriteRule (.*) http://www.mydomain.com%1$1 [L,R=301]
查看更多
登录 后发表回答