skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    @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]
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search