Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Can someone please help with trying to use mod rewrite so is rewritten to and to

Currently my .htaccess is:

RewriteEngine On

# Remove www
RewriteCond %{HTTP_HOST} ^$ [NC]
RewriteRule ^(.*)$$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

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

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, 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 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

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.