jdauphant / ansible-role-nginx

Ansible role to install and manage nginx configuration
655 stars 302 forks source link

Multiple server blocks #187

Closed tkgalk closed 7 years ago

tkgalk commented 7 years ago

I need to setup http -> https redirect by using multiple server blocks, how would it look like when using nginx_sites (multiple sites, 2x static websites + 3x Node.js APIs)?

I'm aiming at something like this:

server {
    listen       80;
    server_name  seafile.example.com;
    rewrite ^ https://$http_host$request_uri? permanent;    # force redirect http to https
    server_tokens off;
}

server {
    listen 443;
    ssl on;
    ssl_certificate /etc/ssl/cacert.pem; 
    ssl_certificate_key /etc/ssl/privkey.pem;
    server_name seafile.example.com;
    server_tokens off;
    # ......
    proxy_pass         http://127.0.0.1:8000;
    proxy_set_header   Host $host;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
    proxy_set_header   X-Forwarded-Proto https;

    proxy_read_timeout  1200s;
}

But it seems nginx_sites allows only for one server block. Any ideas?

teadur commented 7 years ago

 nginx_sites:
        http.xxx.tld:
            - |
              listen 80;
              server_name x1.xxxx.tld x2.xxxx.tld;
              return 301 https://$host$request_uri;
        x1.xxxx.tld:
            - |
              listen 443 default ssl;
              server_name x1.xxxx.tld;
              ssl on;
              root /var/www/x1.xxxx.tld/www;
              location / { try_files $uri $uri/ /index.html /index.php; index index.php;}
              ssl_certificate_key /etc/ssl/private/x1.key;
              ssl_certificate /etc/ssl/certs/x1.crt;
        x2.xxxx.tld:
            - |
              listen 443 ssl;
              server_name x2.xxxx.tld;
              ssl on;
              root /var/www/x2.xxx.tld/www;
              location / { try_files $uri $uri/ /index.html /index.php; index index.php;}
              ssl_certificate_key /etc/ssl/private/x2.key;
              ssl_certificate /etc/ssl/certs/x2.crt;
jdauphant commented 7 years ago

:+1:

And you can event use a custom template if you have lot of that case https://github.com/jdauphant/ansible-role-nginx#9-site-configuration-using-a-custom-template

tkgalk commented 7 years ago

Yeah, the first answer is exactly what's needed. It creates separate files in sites-enabled though, but that's fine.