554

I would like to redirect www.example.com to example.com. The following htaccess code makes this happen:

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

But, is there a way to do this in a generic fashion without hardcoding the domain name?

Paulo Boaventura
  • 1,365
  • 1
  • 9
  • 29
deepwell
  • 20,195
  • 10
  • 33
  • 39
  • 71
    It's important to be aware that if you don't use a www (or some other subdomain) then all cookies will be submitted to every subdomain amd you won't be able to have a cookie-less subdomain for serving static content thus reducing the amount of data sent back and forth between the browser and the server. Something you might later come to regret: http://twitter.com/codinghorror/statuses/1637428313 – Sam Hasler Apr 28 '09 at 23:44
  • 4
    Another thing to consider, make sure you're setting the canonical name without the www in your pages, to avoid a possible duplicate content penalty. Also if you have absolute urls in your links make sure they're all non-www as well. – Jeremy Morgan Dec 06 '12 at 00:42
  • 1
    On my mind its better to keep the explicit redirection, especially when copying the configuration for another domain, that might require different tuning (www domain is better in some cases) http://www.weboptimizer.ch/2014/01/redirection-www/ – snowflake Mar 11 '14 at 09:51
  • Any reason why this solution would work for all cases except the root url? For example http://www.domain.com does not piont to http://domain.com, whereas http://www.domain.com/page1 does redirect to http://domain.com/page1. – Jeff Solomon Aug 26 '14 at 23:18
  • 1
    If you wish to redirect www to non-www whilst maintaining the protocol (HTTP or HTTPS) then see this related question: [Redirecting www to non-www while maintaining the protocol HTTP or HTTPS](https://stackoverflow.com/questions/30274281/redirecting-www-to-non-www-while-maintaining-the-protocol-http-or-https) – MrWhite Jan 22 '19 at 21:46
  • Generic htaccess redirect for `www` or `non-www` https://helponnet.com/2019/06/06/enforce-non-www-with-htaccess/ – Amit Verma Aug 20 '21 at 07:29

25 Answers25

1023
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Same as Michael's except this one works :P

Volomike
  • 23,743
  • 21
  • 113
  • 209
  • 18
    If it does not work, you are probably missing the `RewriteEngine On` precursor to make it work. – hendry May 25 '10 at 09:02
  • 9
    @Ben, how would I use this in reverse, to *add* www to a non-www website? – anarkhos Mar 17 '11 at 21:41
  • 19
    It redirects `http://www.domain.com/` to `http://domain.com//`. You should add `/` to the `RewruteRule`. This works for me `RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]`. – Vladimir Prudnikov May 28 '11 at 09:37
  • The extra slash added by Vladimir prevented it from working for me, and I didn't see a double slash from Ben's version. – Andy Swift Nov 30 '11 at 09:14
  • 16
    I was having the same problem as Vladimir by it redirecting to `http://domain.com//` with the double slashes. So I did `RewriteRule ^(.*)$ http://%1$1 [R=301,L]` and it seems to be working so far – bobfet1 Mar 22 '12 at 13:59
  • @anarkhos A bit late.. but this does it in reverse (add's WWW to domains). RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www\.%{HTTP_HOST}/$1 [R=301,L] – Wireblue Aug 01 '12 at 07:05
  • In order to keep it working also on localhost and other computers/devices connected to the lan, I added these rules: [FIRST RULE] RewriteCond %{HTTP_HOST} \. [SECOND RULE] RewriteCond %{HTTP_HOST} !^192.+$ [NC] – Marco Panichi Apr 05 '13 at 06:06
  • 5
    Please use the following solution rather than rewrite engine, it is much more faster while being elegant: http://stackoverflow.com/questions/1100343/apache-redirect-from-non-www-to-www – Birla Jul 20 '14 at 15:23
  • Ben's answer works for me as is, I don't observe @Vladimir's issue. Can anybody clarify? – matteo Nov 05 '14 at 02:11
  • Surely it's wise to make the `HTTP_HOST` pattern match `^www\.(.+)$` so that you require a domain name? – Bobulous May 01 '15 at 19:09
  • 2
    This drops the subfolder www.example.com/sub/index.php becomes example.com/index.php – Dss Jun 02 '16 at 16:17
  • 2
    In 2018, this should now be https:// on the last line. I got caught in a sneaky mixed-content warning using this code as-is along with a separate HTTPS redirect. – William Entriken Mar 13 '18 at 17:49
  • 2
    @matteo @Vladimir's double slash issue is caused by trying to use these directives in a _server_ (or _virtualhost_) context. The above directives are written for `.htaccess` (a _directory_ context). If you are in a server context then you probably shouldn't be using mod_rewrite for this task, instead use mod_alias `Redirect` directives in the appropriate vhost, as @Birla links to above. – MrWhite Jan 21 '19 at 15:17
  • Must read `htaccess tutorial` for beginners . https://helponnet.com/2021/04/15/htaccess-tutorial-for-beginers/ – Amit Verma Jan 09 '22 at 18:39
124

But if we need to do this for separate http and https:

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

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Nhan
  • 3,595
  • 6
  • 30
  • 38
Andron
  • 6,413
  • 4
  • 43
  • 56
  • 2
    www.example.com/ redirects to example.com// Any way to remove the extra slash? – Bobby S Jun 07 '13 at 05:55
  • Good question. I guess the quick solution will be to use additional rules (i.e. only for this case) before these described above. E.g.: `RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www.example.com/$ [NC] RewriteRule ^(.*)$ http://www.example.com [R=301,L]` ... – Andron Jun 13 '13 at 08:59
  • 4
    @BobbyS I used the solution in [this article](https://simonecarletti.com/blog/2016/08/redirect-domain-http-https-www-apache/). It redirects www and HTTP to non-www HTTPS and also handles the trailing `/`. – totymedli Mar 04 '18 at 08:25
  • You would only get an extra slash (at the start of the URL-path), if you'd placed these directives directly in the server config (or virtualhost). In `.htaccess` you should not be getting an extra slash. (Just to note, if you are performing this redirect in the server config then you probably shouldn't be using mod_rewrite to begin with... a simple mod_alias `Redirect` in the appropriate vhost container would be more efficient and less prone to error.) – MrWhite Jan 21 '19 at 15:04
  • I am currently using this following code, however, it is only covering the home page. When I go to a blog article via http instead of https, I get security warning. RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://www.%1/$1 [R=301,L] – Rookie Recruits Jan 03 '23 at 18:30
  • Just wanted to tag some of the participants on this response. @Andron – Rookie Recruits Jan 03 '23 at 20:02
73

Redirect non-www to www (both: http + https)

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Dmytro
  • 5,443
  • 2
  • 52
  • 50
  • 4
    @nightcoder This is because my solution for inverse redirect (from non-www to www) as opposed to Andron's – Dmytro Nov 24 '13 at 18:41
  • 3
    Note: this solution might cause some problems if you intend to use subdomain names for other purposes. E.g., app.yourdomain.com will be redirected to www.app.yourdomain.com. – Marty ZHANG Sep 25 '14 at 07:11
  • 4
    This is the exact opposite of an answer to the question. – John Nov 07 '17 at 22:44
  • I had to add `RewriteEngine On` and `RewriteBase /`, but otherwise worked well. – overthink May 21 '18 at 01:57
47

If you want to do this in the httpd.conf file, you can do it without mod_rewrite (and apparently it's better for performance).

<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

I got that answer here: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507

Community
  • 1
  • 1
William Denniss
  • 16,089
  • 7
  • 81
  • 124
34

Here are the rules to redirect a www URL to no-www:

#########################
# redirect www to no-www
#########################

RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]

Here are the rules to redirect a no-www URL to www:

#########################
# redirect no-www to www
#########################

RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]

Note that I used NE flag to prevent apache from escaping the query string. Without this flag, apache will change the requested URL http://www.example.com/?foo%20bar to http://www.example.com/?foo%2250bar

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    can you write code to redirect http to https along with redirect www to non-www – HYDER ALI Apr 14 '18 at 09:01
  • Change the http:// to https:// to force it to HTTPS when it changes. You'll also want to add a regular http->https redirect for traffic that isn't being redirected by these rules. – diamondsea May 14 '19 at 14:24
13
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]

The RewriteCond captures everything in the HTTP_HOST variable after the www. and saves it in %1.

The RewriteRule captures the URL without the leading / and saves it in $1.

Volomike
  • 23,743
  • 21
  • 113
  • 209
Michael Cramer
  • 5,080
  • 1
  • 20
  • 16
  • 2
    `sans leading "/"` - In `.htaccess` (as stated in the question) there is no leading `/`, so the pattern never matches and the redirect never happens. (There is only a leading slash in a _server_ or _virtualhost_ context.) Also, if you have any mod_rewrite directives after this then you will need the `L` flag. – MrWhite Jan 20 '19 at 22:15
10

Try this:

RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]

If the host starts with www, we stick the whole host onto the start of the URL, then take off the "www."

Greg
  • 316,276
  • 54
  • 369
  • 333
  • 1
    RoBorg, unfortunately your settings don't work, if I try this: http://www.example.com/hello/world I end up here: http://example.com/hello/world/world I also had to add a slash after %{HTTP_POST} in the First RewriteRule – deepwell Oct 27 '08 at 23:12
  • 2
    I'm using Apache/2.2.9 (Unix). It works for www.website, which redirects to website But for the following: http://www.website/test -> goes to: http://www.websitetest/ I fixed this by adding another / Second error: http://www.website/test/n goes to http://www.websitetest/n/n – deepwell Nov 12 '08 at 22:36
  • 1
    Same issue as @deepwell with this one. – neemzy Oct 21 '14 at 18:17
  • The issues that earlier readers are having is because these directives are intended for the server config (or vhost), not `.htaccess`. In a _directory_ context (`.htaccess`) you should change the first `RewriteRule` to read: `RewriteRule ^(.*)$ %{HTTP_HOST}/$1 [C,DPI]` (requires Apache 2.2.12+). Note the addition of the slash and the `DPI` (Discard Path Info) flag - to prevent part of the URL-path being seemingly duplicated (which is in fact "path-info") as stated in earlier comments. However, there are simpler directives - as covered in the other answers. – MrWhite Jan 20 '19 at 23:25
9

Complete Generic WWW handler, http/https

I didn't see a complete answer. I use this to handle WWW inclusion.

  1. Generic. Doesn't require domain info.
  2. Forces WWW on primary domain: www.domain.com
  3. Removes WWW on subdomains: sub.domain.com
  4. Preserves HTTP/HTTPS status.
  5. Allows individual cookies for domain / sub-domains

Please let me know how this works or if I left a loophole.

RewriteEngine On
RewriteBase /

# Force WWW. when no subdomain in host
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Remove WWW. when subdomain(s) in host     
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)(.+\.)(.+\.)(.+)$ [NC]
RewriteRule ^ %1%3%4%5%{REQUEST_URI} [R=301,L]
Gregor Macgregor
  • 495
  • 6
  • 12
7

There can be a lot of misinformation out there about htaccess redirects, I find. First off, make sure your site is running on Unix using Apache and not on a Windows host if you expect this code to work.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]

RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

(Make sure there are no line spaces between each line of text, though; I have added an extra space between lines so it renders okay in this window.)

This is one snippet of code that can be used to direct the www version of your site to the http:// version. There are other similar codes that can be used, too.

Donny Kurnia
  • 5,260
  • 5
  • 35
  • 52
4

www to non www with https

RewriteEngine on

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

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Rajith Ramachandran
  • 1,319
  • 1
  • 9
  • 10
4
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/subfolder/$1 [R=301,L]

For subfolder

pelajar
  • 41
  • 1
  • 2
3

For those that need to able to access the entire site WITHOUT the 'www' prefix.

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

Mare sure you add this to the following file

/site/location/.htaccess 
Rick
  • 12,606
  • 2
  • 43
  • 41
  • 2
    This example is not complete - you are not setting the `protossl` environment variable (this is not a standard/server variable). This will always be empty, so will always redirect to `http`. (The idea behind setting `protossl` earlier in the code is for when you want to preserve the protocol when redirecting. However, these days you probably should be redirecting to `https` all the time.) – MrWhite Jan 21 '19 at 13:30
3

Using .htaccess to Redirect to www or non-www:

Simply put the following lines of code into your main, root .htaccess file. In both cases, just change out domain.com to your own hostname.

Redirect to www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^domain\.tld [NC]
  RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]
</IfModule>

Redirect to non-www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.domain\.tld [NC]
  RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]
</IfModule>
Manifest Man
  • 873
  • 10
  • 16
Rohallah Hatami
  • 525
  • 6
  • 12
2

I used the above rule to fwd www to no www and it works fine for the homepage, however on the internal pages they are forwarding to /index.php

I found this other rule in my .htaccess file which is causing this but not sure what to do about it. Any suggestions would be great:

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]
Oldskool
  • 34,211
  • 7
  • 53
  • 66
Luke
  • 21
  • 1
2
RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

If you want to remove www on both http and https , use the following :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

This redirects Non ssl

to

And SSL

to

on apache 2.4.* you can accomplish this using a Redirect with if directive,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
2

use: Javascript / jQuery

// similar behavior as an HTTP redirect
window.location.replace("http://www.stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Or .htaccess:

RewriteEngine On
RewriteBase /
Rewritecond %{HTTP_HOST} ^www\.yoursite\.com$ [NC]
RewriteRule ^(.*)$ https://yoursite.com/$1 [R=301,L]

and The PHP method:

$protocol = (@$_SERVER["HTTPS"]    == "on") ? "https://" : "http://";

if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
    header('Location: '.$protocol.'www.'.$_SERVER    ['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
    exit;
}

Ajax

$.ajax({
    type: "POST",
    url: reqUrl,
    data: reqBody,
    dataType: "json",
    success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
        else {
            // data.form contains the HTML for the replacement form
            $("#myform").replaceWith(data.form);
        }
    }
});
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Universal Omega
  • 206
  • 1
  • 5
  • 26
1

If you are forcing www. in url or forcing ssl prototcol, then try to use possible variations in htaccess file, such as:

RewriteEngine On
RewriteBase /

### Force WWW ###

RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

## Force SSL ###

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

## Block  IP's ###
Order Deny,Allow
Deny from 256.251.0.139
Deny from 199.127.0.259
vladkras
  • 16,483
  • 4
  • 45
  • 55
mystique
  • 96
  • 8
  • Apache can listen another port, e.g. 81. So instead of `RewriteCond %{SERVER_PORT} 80` I suggest to use such more universal check: `RewriteCond %{HTTPS} off` – Andron Dec 08 '15 at 10:03
1

This is updated to work on Apache 2.4:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

The only change vs Michael's is to remove the [NC], which produces the "AH00665" error:

NoCase option for non-regex pattern '-f' is not supported and will be ignored

Community
  • 1
  • 1
William Entriken
  • 37,208
  • 23
  • 149
  • 195
  • The earlier answer did not need "updating to work on Apache 2.4". The "warning" you are quoting (AH00665) relates to a different directive (eg. if you had something like `RewriteCond %{REQUEST_FILENAME} !-f [NC]`). The `NC` flag makes little difference in the above, however, the reason the `NC` flag _should_ be used here is to catch the small fraction of bot traffic that (incorrectly) sends an uppercase hostname. – MrWhite Jan 21 '19 at 13:44
1

The selected answer and many other solutions here dropped the the part of the url after /, so basically it always redirected to main domain, at least for me.. So i am adding working sample respecting full path after slash..

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [L,R=301]
luky
  • 2,263
  • 3
  • 22
  • 40
1

The only way I got it to work...

RewriteEngine On
RewriteCond %{HTTP_HOST} ^site\.ro
RewriteRule (.*) http://www.site.ro/$1 [R=301,L]
wattostudios
  • 8,666
  • 13
  • 43
  • 57
sulfy
  • 11
  • 1
1

Alternative approach if .htaccess customization is not ideal option:

I've created simple redirect server for public use. Just add A or CNAME record:

CNAME   r.simpleredirect.net
A       89.221.218.22

More info: https://simpleredirect.net

Bobík
  • 1,828
  • 20
  • 19
1

Add

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]

to your .htaccess before any other rule.

Pushkraj Jori
  • 187
  • 1
  • 12
0

Added if localhost, ignore redirection (for development purpose in local environment). If not localhost AND (not https OR it’s www), redirect to https and non-www.

RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} !localhost [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Jeaf Gilbert
  • 11,495
  • 19
  • 78
  • 105
0

I am not sure why u want to remove www. But reverse version would be:

# non-www.* -> www.*, if subdomain exist, wont work
RewriteCond %{HTTP_HOST} ^whattimein\.com
RewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]

And advantage of this script is: if u have something like test.whattimein.com or any other (enviroments for developing/testing) it wont redirect U to the original enviroment.

local
  • 17
  • 1
  • 2
    Whether the www subdomain should be included or not is really a matter of personal preference and can depend on the domain name and target audience. The generic code posted above for redirecting www to none-www also handles test environments OK, since the redirect only occurs when the "www." subdomain is encountered. – MrWhite Jan 22 '12 at 17:57
  • 1
    This question does the opposite of what the user is asking, which is only polluting the post. – Vadim Mar 09 '18 at 21:30
-3

Hi you can use following rules on your htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Chirag Parekh
  • 498
  • 6
  • 13
  • The question is asking for a "generic" solution that does not include the domain name. Your solution also does the _complete opposite_ of what is asked for in the question (non-www to www, rather than www to non-www) without explanation. – MrWhite Jan 20 '19 at 23:35