Undisputed Shadow
Undisputed Shadow

Reputation: 61

Redirect from http to https without www using .htaccess

I have application based on PHP and Apache. If requested link is not directory or file, all requests go to index.php file. I wanna redirect all requests from http to https and without www.

Valid link for me:

  1. https://someaddress.org

Started from following links invalid for me(sorry my reputation is very small and i cant post more 2 links):

  1. http://
  2. http://www.
  3. www.

My htaccess looks like that

AddDefaultCharset UTF-8

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index.php [L]

How i can do redirects to https and without www?

Upvotes: 2

Views: 1807

Answers (3)

Bhavesh
Bhavesh

Reputation: 914

First redirect all request with WWW to https without WWW

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

Now redirect all http request without WWW to https without WWWW

# For http://yourdomain.com
RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]

Add above code one by one in .htacess file in sequance to redirect your all request to https without www

I used "R=301" for permanent redirection

Upvotes: 0

Francisco Félix
Francisco Félix

Reputation: 2413

You can cover the http to https part with the SSLRequireSSL directive.

<Directory />
  SSLRequireSSL
</Directory>

If the problem is the htaccess file and not the rewriting rules you can stop using the .htaccess file and move the rewriting rules to the apache configuration files.

If you just dont want or can use rewriting rules, and as the vast majority of php applications needs a configuration file included in every single script (configuration vars or user control as examples) you can use this file to get the requested resource and strip the www. part if the domain name starts with them.

I can provide a php code example if the include file may be the solution you need.

Upvotes: 0

anubhava
anubhava

Reputation: 784998

Have another rule for http->http and www removal:

AddDefaultCharset UTF-8

RewriteEngine on
RewriteBase /

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://someaddress.org%{REQUEST_URI} [L,NE,R=301]

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

Upvotes: 1

Related Questions