1

I am trying to force all urls to https, www, no trailing slashes and ultimately direct all requests to a php controller page. Server uses LiteSpeed. I have tried this, but it does not seem to completely function as expected. It appears to handle trailing slash issue and https, but not the www.

# Turn on Rewrite Engine
RewriteEngine on

# Force a trailing slash except on files and directories that actually exist on server
RewriteCond %{REQUEST_URI} !(.+)/$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ https://www.example.com/$1/ [R=301,L]

# Force HTTPS and WWW 
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{HTTPS} off  
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

# Redirect all requests to php controller except files and directories that actually exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

So, how can I make sure that all requests are handled by my controller page, and force url to be https, www, and add trailing slash and do so in one redirect?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
user5919866
  • 69
  • 1
  • 8
  • What exactly isn't working for you? – anubhava Aug 03 '22 at 20:50
  • @anubhava I have discovered it actually is working that is was an ssl issue on the non-www domain name. Fixed that and the htacess is working as it's suppose to, although it does 2 redirects. I would like for it to do just one. – user5919866 Aug 04 '22 at 15:47

2 Answers2

0

although it does 2 redirects. I would like for it to do just one.

You may use this code to do all redirects in a single rule and single redirect:

RewriteEngine On

# add www, https, trailing slash
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*?)/?$ https://www.%1/$1/ [R=301,L,NE]

# rewrite all requests to php controller
# except files and directories that actually exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [L]

Make sure to clear your browser cache before testing this change.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

@anubhava answer didn't work on my site. It broke links to resources, etc., but this did work with only one redirect.

# Force www, https, trailing slash except on files and directories
RewriteCond %{REQUEST_URI} !(.+)/$ [OR,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{HTTPS} off  
RewriteRule ^(.*)$ https://www.example.com/$1/ [R=301,L]

# Redirect all requests to php controller except files and directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
user5919866
  • 69
  • 1
  • 8