Search code examples
apache.htaccess

Modify existing .htaccess so that it ignores subdomains


I have the following .htaccess file in place, and whilst I know it is nowhere near optimal (and probably a bit cringeworthy) - it just works.

# Prevents public viewing of .htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>

# Custom 404 page
ErrorDocument 404 https://www.domain.com/404/

# Turn on rewriting and set rewriting base
RewriteEngine On
RewriteBase /

# Force WWW
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]{2,4})$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

# Force WWW and HTTPS
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L]

# Remove .php extension
RewriteRule ^(properties)/(all|location1|location2|location3)/(all|1|2|3|4|5|6|7|8|9)/(asc|desc) $1.php?location=$2&bedrooms=$3&sort-by=$4
RewriteRule ^(properties)/(all|location1|location2|location3)/(all|1|2|3|4|5|6|7|8|9) $1.php?location=$2&bedrooms=$3
RewriteRule ^(properties)/(all|location1|location2|location3) $1.php?location=$2
RewriteRule ^(view-property)/(.*)/(print-view) $1.php?id=$2&print=true
RewriteRule ^(view-property)/(.*)/ $1.php?id=$2
RewriteRule ^(.*)/$ $1.php

Our new website is now ready to be pushed to our newly created staging environment for testing. In this instance it would be staging.domain.com but we're having problems actually accessing this staging URL.

EDIT - Just to clarify, the problem is that accessing staging.domain.com redirects to https://www.domain.com.

We believe the problem is caused by the rewrite rules we have in place above. I have researched a few possible solutions include adding additional conditions to the existing rewrite rules such as:

RewriteCond %{HTTP_HOST} !^staging\.domain\.com

or adding a new condition/rule such as:

RewriteCond %{HTTP_HOST} ^staging\.domain\.com [NC]
RewriteRule ^(.*) - [L]

but unfortunately none of these have worked. Working with .htaccess files is really not my strong suit, so if anyone could offer any assistance that would be great.

P.S. The new site is powered by Laravel 5.3 so I will be getting rid of the terrible attempt at rewriting rules (those at the bottom) when we go live!


Solution

  • Your top rules must be changed to this to remove hardcoded domain name in target URL:

    # Turn on rewriting and set rewriting base
    RewriteEngine On
    RewriteBase /
    
    # Force WWW and HTTPS
    RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
    
    # Remove .php extension and rest of the rewrite rules