Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Can someone please help with trying to use mod rewrite so foo.domain.com is rewritten to domain.com/p.php?s=foo and foo.domain.com/bar to domain.com/p.php?s=foo&p=bar?

Currently my .htaccess is:

RewriteEngine On

# Remove www
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

# Rewrite subdomain etc.
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteRule ^([^/]+)/?$ p.php?s=%1&p=$2 [QSA,L,NC]

But I can't work out how to grab the second variable (being optional and after a slash at the end of the URI. I've tried changing the end of the condition to ?/(.*)$, but to no avail and my mod rewrite skills are certainly naff!

share|improve this question

2 Answers 2

If it's OK to get the p parameter empty in case of empty URL part, following should work:

# Rewrite subdomain etc.
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !p.php
RewriteRule ^(.+/)?([^/]*)$ p.php?s=%1&p=$2 [QSA,L,NC]

In case you want to completely left out the p in case of direct hit to foo.domain.com, you need to add to the above also special rule for this case, matching empty URL - like this:

RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !p.php
RewriteRule ^$ p.php?s=%1 [QSA,L,NC]
share|improve this answer
Cheers, that works well! One tiny issue though, if a trailing slash is added it redirects to foo.domain.com/foo/bar which is very strange. I've tried a few things to remove the trailing slash before your rule is run but couldn't get it to work. Know how to get that to work? So basically ensuring that there isn't a slash at the end before your rewrite? Principally, however, it's great. I should've mentioned that it was a CMS-like thing which needs variables rather than the actual strings, but you worked that out anyway :) –  Rich Nov 14 '12 at 21:15
@Rich nice to hear, it helped... you possibly look for the rule RewriteRule ^(.+)/$ $1 [L]? –  Kamil Šrot Nov 14 '12 at 21:28

That stops the weird redirect but doesn't remove the slash from the URI (I'm thinking from an SEO perspective in that multiple URIs for duplicate content are bad :) ) does it need a redirect? I tried adding the R=301 flag but that didn't work. Any ideas?

(Sorry for adding answer, "add comment" button has literally disappeared!)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.