Search code examples
apache.htaccessmod-rewritehttpsno-www

Forcing HTTPS & NON-WWW on a subfolder with a different domain rewrites incorrectly


I already have a Wordpress website installed to /home/USER/public_html/ and the .htaccess inside the folder looks like:

# BEGIN Redirect Alias Site to Specific Folder
    RewriteCond %{HTTP_HOST} customwebsite.com$ [NC]
    RewriteRule ^(.*)$ /customwebsite/$1 [L]
# END Redirect Alias Site to Specific Folder

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

The redirect alias rules in the .htaccess file above allows me to route my alias domain to use a different folder thus allowing mulitple websites to be ran from the same cPanel account.

In the folder /home/USER/public_html/customdomain/ I've set the .htaccess rules to:

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /customdomain/
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /customdomain/index.php [L]
</IfModule>
# END WordPress

It works perfectly fine; however if I try and FORCE HTTPS and NON-WWW using every set of rules I can find on the internet... for example:

<IfModule mod_rewrite.c>
    # Force HTTPS & NON-WWW
    RewriteEngine On
    RewriteCond %{HTTPS} !=on  [OR]
    RewriteCond %{HTTP_HOST} !^customdomain\.com$ [NC]
    RewriteRule ^ https://customdomain.com%{REQUEST_URI} [R=301,L]
</IfModule>

and what I can make myself and then try and load any of the following:

  • http://customdomain.com
  • https://www.customdomain.com
  • http://www.customdomain.com

They all redirect to:

  • https://customdomain.com/customdomain/

Which is partly correct, but partly wrong. It shouldn't have the folder at the end of the domain which causes problems because the URL is now incorrect.

Sure if I remove the %{REQUEST_URI} it fixes the redirect issue but if I am using Wordpress for example every URL will be wrong and will throw up a 404 page not found.

How can I fix the Force HTTPS & NON-WWW to allow for this scenario?


Solution

  • You can use this rule as your first rule in /customdomain/.htaccess:

    RewriteEngine On
    RewriteBase /customdomain/
    
    # Force HTTPS & NON-WWW
    RewriteCond %{HTTPS} !=on  [OR]
    RewriteCond %{HTTP_HOST} !^customdomain\.com$ [NC]
    RewriteRule .* https://customdomain.com/$0 [R=301,L,NE]
    
    RewriteRule ^index\.php$ - [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    

    Make sure to clear your browser cache or use a new browser for testing.