M Irfan
M Irfan

Reputation: 23

redirecting from www to non-www urls with .htaccess

I am redirecting an application with following code on my .htaccess file, the page is supposed to do the followings:

  1. replace .php extension with .html
  2. redirect from http to https
  3. redirect from www to non-www urls

The extension .html is working fine and it is redirecting from http to https but the issue is to redirect from www to non-www, it is working properly on main url but when there is reference to a file then it is not working.

Say when i write www.ntestechnologies.com i get my desire url that is https://ntestechnologies.com but when i write www.ntestechnologies.com/index.html i get this https://www.ntestechnologies.com/index.html i don't need the www in this url as well please guide me, here is the code on htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.ntestechnologies\.com$
RewriteRule ^/?$ "https\:\/\/ntestechnologies\.com\/$1" [R=301,L]

RewriteRule ^(.*)\.html$ $1.php [nc]

Upvotes: 1

Views: 414

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74088

You need only one RewriteEngine On.

You cannot use HTTP_HOST or REQUEST_URI in a RewriteRule. If you need to capture these values, you must do so in a RewriteCond

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)(.+)
RewriteRule .* https://%1/$0 [R,L]

RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule .* https://%1/$0 [R,L]

This removes the leading www, if present. At the same time, it redirects to HTTPS.

Upvotes: 1

kjetilh
kjetilh

Reputation: 4976

RewriteEngine On

# Redirects from HTTP to HTTPS. We use %{SERVER_PORT} as it's more reliable than %{HTTPS}
RewriteCond %{SERVER_PORT} !^443$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

# Redirects www.example.com/... to example.com/...
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule .* https://%1%{REQUEST_URI} [R,L]

RewriteRule ^(.*)\.html$ $1.php [nc]

Upvotes: 0

Related Questions