Nilesh K
Nilesh K

Reputation: 146

Nginx Permanent Redirect (NON-WWW to WWW) not working

Hi Guys I want my all NON-WWW url request to move permanently and also rewrite to WWW and I have tried to follow existing solutions at these as well Nginx no-www to www and www to no-www but still it did not work for me.

e.g. I want example.com or example.com/* to rewrite to www.example.com or www.example.com/*

I am running PHP-FPM with nginx and memcache

below is my config

server {
listen 80;
server_name abc.com;
return 301 http://www.example.com$request_uri;
}

server {
        listen 80;
        server_name www.example.com;

        root /srv/www/abc;
        index index.php index.html index.htm;
.......
}

Below is my curl response

neel:~ nilesh$ curl -I http://example.com
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Fri, 21 Aug 2015 19:00:54 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.9-1ubuntu4.11
X-Drupal-Cache: HIT
Etag: "1440178291-0"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Link: <http://example.com/>; rel="canonical",<http://example.com/>; rel="shortlink"
Cache-Control: public, max-age=1800
Last-Modified: Fri, 21 Aug 2015 17:31:31 +0000
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Vary: Cookie
Vary: Accept-Encoding

Upvotes: 1

Views: 565

Answers (1)

Nilesh K
Nilesh K

Reputation: 146

I have finally SOLVED my issue. I checked my nginx.conf and it was pointing to /etc/nginx/sites-enabled and /etc/nginx/conf.d

my nginx.conf->

 ##
        # Virtual Host Configs
        ##
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

I finally copied my file from sites-available to folder sites-enabled. infact I kept it synced.

below is the code i used under my server tag

server {
listen 80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}

server {
        listen 80;
        server_name www.example.com;
        #listen [::]:80 default_server ipv6only=on;
        root /srv/www/example;
#rest config goes below

.......

Now all my non-www traffic is 301 permanently moved and rewrite to www with the above code.

I made a curl call to non-www and I got the following correct response.

neel:~ nilesh$ curl -I http://example.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Thu, 27 Aug 2015 08:39:38 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://www.example.com/

Upvotes: 1

Related Questions