nginx - rewrite domain.com:port to sub.domain.com

2019-04-02 01:35发布

问题:

How can i rewrite a domain with a port to a subdomain?

e.q.: domain.com:3000 to sub.domain.com ?

thanks for your help! :)

greetz

回答1:

If you actually want to redirect (301 or 302) your web traffic

You create a server {} section listening on port 3000 and you just redirect it to another server {} section that is listening on port 80. In each server {} section set the listen property appropriately. I guess you are trying to handle the redirection within à single server section and according to this page the listen directive applies to a server context

If you want to use nginx as a proxy

Then what you are looking for is the proxy_pass directive. Here is a sample configuration extracted from an config I have to use nginx as a proxy for my rails app (thin). Basically my app runs locally (but it would also work on a remote host) on port 3200 and the relevant nginx config part looks as follow:

  upstream my-app-cluster
  {
      server localhost:3200;
  }  
  server
  {
    listen       80;
    server_name mydomain.com;

    root /root/to/public/folder;

    access_log  /my/app/log/folder/myapp.log;

    location / {
      proxy_set_header  X-Real-IP  $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;

      if (-f $request_filename/index.html) {
        rewrite (.*) $1/index.html break;
      }
      if (-f $request_filename.html) {
        rewrite (.*) $1.html break;
      }
      if (!-f $request_filename) {
        proxy_pass http://my-app-cluster;
        break;
      }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }

  }


回答2:

You could use Passenger in nginx to delivery the Ruby app - that's the method we are currently using.

http://www.modrails.com/