Reputation: 205
I am having difficulty getting several mod_rewrite rules to work together in my .htaccess files. Throughout the enitre site I want to drop the "www." from all URLs. I am using the following at the document root:
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301]
Then, in one folder "/help" I want to do 2 rewrites:
So in domain.com/help I have the following:
Options +FollowSymLinks
RewriteRule ^([0-9]+)/?$ index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$ index.php?category=$1 [NC,L]
The above 2 .htaccess files work for:
www.domain.com to domain.com
domain.com/help/1 to domain.com/index.php?question=1
domain.com/help/category/example to domain.com/index.php?category=example
But, this does not work when I need to combine the 2 rewrites to both drop the "www." and to rewrite the subfolders to a url variable. e.g.:
www.domain.com/help/1 to domain.com/index.php?question=1
gives a 500 error.
Where did I go wrong? And, is this best to do with 2 .htaccess files, or can/should the 2 files be combined into 1 .htaccess file at the document root?
Upvotes: 4
Views: 4610
Reputation: 143856
It looks like what's happening is the rules in the .htaccess file in the /help folder is getting applied because you're requesting something in that folder, so the parent folder's rules won't get applied. You can have your parent rules passed down if you add a RewriteOptions Inherit
in your /help folder's .htaccess:
Options +FollowSymLinks
RewriteOptions Inherit
RewriteRule ^([0-9]+)/?$ index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$ index.php?category=$1 [NC,L]
However, the inherited rules may not be applied in the order that you're expecting. For example, if you request http://www.domain.com/help/1/ you'll end up getting redirected to http://domain.com/index.php?question=1 which may not be what you want if you are trying to make SEO friendly URLs by hiding the query string.
Your best bet may be to move the stuff in the /help folder into the one in your document root so that you can control the order that the rules will be applied:
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301]
RewriteRule ^help/([0-9]+)/?$ /index.php?question=$1 [NC,L]
RewriteRule ^help/category/([^/\.]+)/?$ /index.php?category=$1 [NC,L]
This ensures the redirect to the non-www domain occurs first, then the /help rules get applied. So when you go to http://www.domain.com/help/1/, you first get redirected to http://domain.com/help/1/ then the help rules get applied and the URI is rewritten to /index.php?question=1
.
Upvotes: 2