d3bug3r
d3bug3r

Reputation: 2586

Redirect https from non www to www

Following were my Nginx server config (not work). I need to redirect https non www to www. So when I visit a site https://example.com, it should redirect me to https://www.example.com.

server {
    listen 443 ssl
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

EDIT: my load balancer: enter image description here

I am using AMI Linux running Ruby on Rails app in AWS. Thanks!!

Upvotes: 0

Views: 417

Answers (2)

Akshath Kumar
Akshath Kumar

Reputation: 519

Please use the below config in your nginx.conf file. Its working fine for me.

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

       location / {
            index       index.html;
            root        /usr/share/nginx/html;  #the location of your app folder
       }


        if ($http_x_forwarded_proto = 'http') {
            return 301 https://www.example.com$request_uri;
        }

}

Upvotes: 3

Aetherus
Aetherus

Reputation: 8888

If you just want to redirect GET requests and throw a 405 (Method not allowed) for non-GET requests:

server {
  listen 443 ssl;
  server_name example.com;
  if ($request_method = GET) {
    return 301 https://www.example.com$request_uri;
  }
  return 405;
}

server {
  listen 443 ssl;
  server_name www.example.com;

  # locations
}

If you want all requests (GET, POST, ...) to be redirected, which is not possible, I suggest that you should try Akshath's method.

Upvotes: 0

Related Questions