Nginx multiple server blocks listening to same port

后端 未结 1 1582
误落风尘
误落风尘 2020-12-08 01:02

I want to run www.example.com and api.example.com on same port 80.

This is what I have. All my googles ping lead to the below

相关标签:
1条回答
  • 2020-12-08 01:31

    Create separately two files (you don't have to, but it will be much clearer) in /etc/nginx/sites-available/www.example.com and /etc/nginx/sites-available/api.example.com

    The api.example.com file's conten

    server {
            listen 80
            server_name api.example.com
            root /var/www/api.example.com/html/example/app; #also add a root dir here
            location / {
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_pass http://127.0.0.1:3836;
            }
    }
    

    The www.example.com's content:

    server {
            listen 80 default_server;
    #       listen [::]:80 default_server ipv6only=on;
    
            root /var/www/example.com/html/example/app;
            index index.html index.htm;
    
            # Make site accessible from http://localhost/
            server_name www.example.com www.example.org;
    
            location / {
                    # First attempt to serve request as file, then
                    # as directory, then fall back to displaying a 404.
                    try_files $uri $uri/ =404;
                    # Uncomment to enable naxsi on this location
                    # include /etc/nginx/naxsi.rules
            }
    
            location /bower_components {
                    alias /var/www/example.com/html/example/bower_components;
            }
    
            location /scripts {
                    alias /var/www/example.com/html/example/scripts;
            }
    
            location /content {
                    alias /var/www/example.com/html/example/content;
            }
    
            location /api {
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_pass http://127.0.0.1:3836;
            }
    }
    

    And finally enable the domains: sudo ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/www.example.com and sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/api.example.com

    0 讨论(0)
提交回复
热议问题