Med
Med

Reputation: 35

htaccess www well in home page but not in other pages

My .htaccess file content

Options +FollowSymLinks -Indexes
RewriteEngine On

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]



# Remove index.php

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]




# Redirect Http To Https
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]



# Redirect Non Www To Www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

my example.com redirected well to www.example.com (Not problem)

my problem when I go to other pages like

example.com/page1/test redirected to www.example.com

(That my problem) I need it redirect me to www.example.com/page1/test

Upvotes: 1

Views: 18

Answers (1)

MrWhite
MrWhite

Reputation: 45829

Your directives are in the wrong order. You need to put your canonical redirects before the front-controller - at the top of the file.

By placing the redirects at the end they are simply never going to get processed for anything other than static files/directories since everything else is routed to index.php.

Your HTTP to HTTPS redirect is also incorrect since you are unconditionally prefixing with the www subdomain.

Also, no need to repeat RewriteEngine throughout the file.

In other words, arrange your directives like this (assuming you are not intending to implement HSTS):

Options +FollowSymLinks -Indexes
RewriteEngine On

# Remove index.php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

# Redirect Non Www To Www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

# Redirect Http To Https
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

It is more efficient to use a regex like ^ to simply be successful for every URL, rather than .* that needs to traverse the entire URL-path - since you are not capturing this.

You will need to clear your browser cache before testing. Preferably test with 302 (temporary) redirects to avoid caching issues.

Upvotes: 1

Related Questions