0

I have finally gotten around to setting up a Nginx reverse proxy to handle the multiple websites I host at my house since I only have one external IP address and everything is working, but what I want to know is if there is a way I can simplify the current configuration for one of my sites that is longer than I feel it needs to be. Any input is greatly appreciated.

server {
  listen 192.168.1.176:80;
  server_name ighfdexplorers.com;
  return 301 https://www.$server_name$request_uri;
}

server {
  listen 192.168.1.176:443 ssl http2;
  server_name ighfdexplorers.com;
  return 301 https://www.$server_name$request_uri;

  ssl_certificate /etc/nginx/ssl/ighfdexplorers/base/fullchain.pem;
  ssl_certificate_key /etc/nginx/ssl/ighfdexplorers/base/privkey.pem;
}

server {
  listen 192.168.1.176:80;
  server_name www.ighfdexplorers.com;
  return 301 https://$server_name$request_uri;
}

server {
  listen 192.168.1.176:443 ssl http2;
  server_name www.ighfdexplorers.com;

  set $upstream 192.168.1.179;

  ssl_certificate /etc/nginx/ssl/ighfdexplorers/fullchain.pem;
  ssl_certificate_key /etc/nginx/ssl/ighfdexplorers/privkey.pem;

  location / {
    proxy_pass_header Authorization;
    proxy_pass https://$upstream;
    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_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;
    client_max_body_size 0;
    proxy_read_timeout 36000s;
    proxy_redirect off;
    proxy_ssl_session_reuse off;
  }
}
  • That's a fairly typical configuration. An http server forwarder, an https server forwarder, and a server to do the actual work. I don't see any need or reason to change it. – Tim Sep 03 '17 at 22:54

1 Answers1

0

You can do a generic catchall redirect for all domains that dont have a server section like so:

server
{
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name .ighfdexplorers.com;
  location /
  {
    return 301 https://$host$request_uri;
  }
}

server
{
  listen 443 ssl http2 default_server;
  listen [::]:443 ssl http2 default_server;

  server_name ighfdexplorers.com;

  if ($host != $server_name)
  {
    return 301 https://$server_name$request_uri;
  }

  ... ssl directives, etc... 
}

Using server_name with a proceeding . tells nginx to match any subdomain prefix, or none. Since it is the default server, this will also match everything else, you may not want this.

The second server is again the default server but for HTTPS, so it will be used for everything that doesn't match. If we then comapre the $host requested to the configured $server_name and they do not match we redirect to the correct name. This way *.ighfdexplorers.com will always redirect to ighfdexplorers.com unless there is a server for that specific name.