Home > Back-end >  How do I combine rewrites (use a subdirectory as root while forcing https and non-www)
How do I combine rewrites (use a subdirectory as root while forcing https and non-www)

Time:09-07

How does one combine .htaccess rewrites to achieve the following:

  • Users visiting the root of a domain (example.com), should see and navigate the content of a subdirectory (example.com/subdirectory).
  • https and non-www should be forced.

This works for using the subdirectory as root:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subdirectory/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /subdirectory/$1

RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]
RewriteRule ^(/)?$ subdirectory/index.html [L]

Questions:

  • Should I add the other two rules (force https and non-www) between "RewriteEngine On" and the first RewriteCond?
  • Does every rule use the original request or is the original request modified with each rule?

CodePudding user response:

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^$ subdirectory/ [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ subdirectory/$1 [L]

Usage = These rules will make all urls to https, non-www and if someone visit example.com it will redirect to example.com/subdirectory.

  • Related