I am trying to set up a my development, staging, and production servers in such a way that I can create a single .htaccess file and use environment-specific variables to determine which rewrite actions to execute. I want to use the name of the specific server to do URL rewrites, but I seem to be running across some problem (likely trivial) that I simply can’t solve.
The goal of this .htaccess file is to:
- Rewrite URL to WWW on production server only
- Send
.htmlfilenames asfooquery vars - Send
.htmfilenames asbarquery vars - Be able to modify or add additional rules to specific servers
Similar to this suggested outline, my htaccess file looks like this:
Options +FollowSymlinks
RewriteEngine On
# Production
# Redirect to WWW on production server
RewriteCond %{SERVER_NAME} =www.domain.com [NC]
RewriteCond %{HTTP_HOST} !^www\.domain.com
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301,NC]
RewriteCond %{SERVER_NAME} www.domain.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.html index.php?foo=$1 [NC,L,QSA]
RewriteRule ^(.+)\.htm index.php?bar=$1 [NC,L,QSA]
# Staging
#RewriteCond %{SERVER_NAME} =staging.domain.com [NC]
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^(.+)\.html index.php?foo=$1 [NC,L,QSA]
#RewriteRule ^(.+)\.htm index.php?bar=$1 [NC,L,QSA]
# Development
RewriteCond %{SERVER_NAME} =localhost [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.html index.php?foo=$1 [NC,QSA,L]
RewriteRule ^(.+)\.htm index.php?bar=$1 [NC,QSA,L]
The problem that I’m having is that no matter which order I list the servers in the .htaccess file, only the first server listed seems to rewrite properly. When deployed on the other servers I am noticing that the foo test case is skipped over and is instead returned as the bar result. I have been able to determine that this seems to be coming from the second RewriteRule in the first server section, but I can’t figure out why.
More information can be provided upon request.
I think maybe you need to replace the SERVER_NAME checks with HTTP_HOST and add a $ to your html/htm checks.