Simone
Simone

Reputation: 21282

htaccess RewriteRule for subdomain

Say I have the following site:

http://example.com/site

that is the same of

http://site.example.com

I was wondering if I could obtain something like this

http://site.example.com/var/

using apache2's mod_rewrite.


Here's my try:

RewriteEngine on
RewriteRule ^([^/\.]+)$ /site/?var=$1

this works like a charm when the URL is http://example.com/site, but since I'm just a beginner I don't know how to get this to work for http://site.example.com.

Any help would be really appreciated.

Upvotes: 1

Views: 6730

Answers (2)

undone
undone

Reputation: 7888

The first part redirect example.com/site/var to site.example.com/var. Second rewrite rule, rewrite your url in site.example.com,

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST}%{REQUEST_URI}   ^(www\.)?example.com/site/(.*)
RewriteRule  (.*)  http://site.example.com/%1  [R=301,L]

RewriteRule ^([^/\.]+)$ /site/?var=$1 [L]

Explanation:
RewriteEngine on
this line turns rewrite engine on. otherwise it may fail to work.
RewriteBase /
this line sets rewrite base. this directive uses when want to set base URL for per-directory rewrites. default value is current physical path but in most cases, URL-base in NOT directly related to physical filename paths, so it's wrong to use default. for example when using virtual directory you should set this option correctly to mod_rewrite act well.

RewriteCond %{HTTP_HOST}%{REQUEST_URI} ^(www.)?example.com/site/(.*)
in this line first apache joins to variable (host address: www.example.com and request URI : /site/var ). then it checks result with pattern I gave. first of result can be www. .after that should be example.com/site/ and at the end it can be anything.

RewriteRule  (.*)  http://site.example.com/%1  [R=301,L]


this line redirects user request to http://site.example.com/%1 with 301 status code. because it has L flag it's the last rewrite rule apache checks.%1 is everything marked by (.*) in rewrite condition.

RewriteRule ^([^/\.]+)$ /site/?var=$1 [L]


this line is the line you put in your question: it rewrites every URL that doesn't have / and dot with /site/?var=$1.

Upvotes: 3

Simone
Simone

Reputation: 21282

I've found a solution:

RewriteBase /

Some hosts need a RewriteBase specification in order to work well. I hope this helps.

Upvotes: 1

Related Questions