Nginx 根据不同的域名来代理转发内部主机-HTTP和HTTPS

一、需求

由于公司只有一个公网,很多 web 项目都想通过 80 或 443 端口来访问,所以需要 Nginx 充当公司网关。

把唯一的公网 IP 80 端口和 443 端口跟 Nginx 网关主机 IP 映射,进行 HTTP 和 HTTPS 代理转发到内部主机中。

配置转发的域名时,需要提前将域名和公网 IP 进行解析绑定才可以。

image-20220209153956886

二、配置文件

//wiki.xxx.net/ 配置

...
   server {
        listen       80;
        server_name  wiki.xxx.net;
	    charset utf-8;
    	access_log  /var/log/nginx/wiki.xxx.net/access.log;

    	location / {
        	try_files /_not_exists_ @backend;
    	}

    	location @backend {
        	proxy_set_header X-Forwarded-For $remote_addr;
        	proxy_set_header Host            $http_host;
        	proxy_set_header X-Forwarded-Proto $scheme;

        	proxy_pass //192.168.101.69:8181;
    	}
...

//app.xxx.net/ 配置

...
    server {
        listen 443 ssl;
        server_name  app.xxx.net;
        charset utf-8;

        access_log  /var/log/nginx/app.xxx.net/access.log;
        ssl_certificate ../conf/cert/7174710_app.xxx.net.pem;
        ssl_certificate_key ../conf/cert/7174710_app.xxx.net.key;

        location / {
                try_files /_not_exists_ @backend;
        }

        location @backend {
                proxy_set_header X-Forwarded-For $remote_addr;
                proxy_set_header Host            $http_host;
                proxy_set_header X-Forwarded-Proto $scheme;

                proxy_pass //192.168.101.70;
        }
    }
...

三、访问测试

访问://wiki.xxx.net/

image-20220209160121542

访问://app.xxx.net/

image-20220209160236957

到此就完成根据域名来代理转发对应的主机了,后续还有其他系统需要对外提供服务的,通过以上配置微调即可。
如有不恰当的地方,还望大佬们在评论区指教,谢谢!

Tags: