如何添加www。使用NginX和SSL域名?

时间:2014-06-10 18:14:22

标签: ruby-on-rails ssl nginx

我有一个VPS,在Ubuntu上使用NginX和Unicorn运行Rails 4应用程序。

由于我希望所有网页都受到SSL保护,因此对http://的所有请求都会转发到https://,这样可以正常运行。

这是我的NginX配置:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events { worker_connections 1024; }

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        server_tokens off;

        server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";
        gzip_types text/plain text/xml text/css text/comma-separated-values;
        upstream app_server { server 127.0.0.1:8080 fail_timeout=0; }

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

        server {
                listen 80;
                server_name myapp.com;
                rewrite ^ https://$server_name$request_uri? permanent;
        }

        server {
                listen 443;
                server_name myapp.com;
                root /home/rails/public;
                index index.htm index.html;

                ssl on;
                ssl_certificate /etc/ssl/myapp.com.crt;
                ssl_certificate_key /etc/ssl/myapp.com.key;

                location / {
                        try_files $uri/index.html $uri.html $uri @app;
                }

                location @app {
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header Host $host;
                        proxy_pass http://app_server;
                 }
        }
}

如何确保将http://myapp.comhttps://myapp.com的所有请求转发到https://www.myapp.com

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以采取以下两种方式:

  • 在您的Rails应用中,检测请求的URI是否包含www并根据该值进行30(1 | 2)重定向(可能最简单)。
  • 在Nginx中创建一个额外的虚拟主机,在myapp.com上进行监听,只让它重定向到www.myapp.com

    服务器{   听443;   server_name myapp.com;   [添加ssl配置]   return 301 https://www.myapp.com $ request_uri; }