ServAce85
ServAce85

Reputation: 1622

Method of using .htaccess to Rewrite Server-Specific URLs is not obeying RewriteCond

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:

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.

Upvotes: 2

Views: 2467

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

I think maybe you need to replace the SERVER_NAME checks with HTTP_HOST and add a $ to your html/htm checks.

# Redirect to WWW on production server
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301,NC]

RewriteCond %{HTTP_HOST} ^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 %{HTTP_HOST} ^staging\.domain\.com$ [NC]
# otherwise, it would look same as Development

# Development
RewriteCond %{HTTP_HOST} ^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]

Upvotes: 3

Related Questions