简体   繁体   中英

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: 在此处输入图片说明

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

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;
        }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM