用Nginx做简单反向代理

本文最后更新于:2022年10月4日 晚上

Nginx是一个很强大的轻量级的Web服务器、反向代理服务器,由于它的内存占用少,启动极快,高并发能力强,在互联网项目中广泛应用。如果想要在一个服务器上布置很多个站点,并且都直接用域名不加端口号,也就是用443/80端口访问,那么反向代理必不可少。本文用搭建 Speedtest-x 服务器来介绍简单的Nginx反代。

首先搭建站点

首先可以看用服务器搭建你自己的SpeedTest测速服务器来搭建自己的网页,但最后是访问 {IP}:{端口}/index.html 进行测速打开网页,这样很不方便。这里我们记住端口号就好。

修改端口的host

对于用服务器搭建你自己的SpeedTest测速服务器这篇文章,我们的站点是可以通过外网来访问端口最终来访问网页的,但既然我们已经要进行反代了,那么对外网开放端口并不是一个很好的选择。我们可以先停止之前的容器。

docker ps查看容器信息,找到对应的容器ID(CONTAINER ID)。

然后docker stop speedtest-x && docker rm speedtest-x或者docker stop 容器ID && docker rm 容器ID

  1. arm架构
    运行 docker run -d -p 127.0.0.1:9001:80 -it --name speedtest-x stilleshan/speedtest-x

  2. amd架构
    运行 docker run -d -p 127.0.0.1:9001:80 -it --name speedtest-x badapple9/speedtest-x

Nginx 反代

新建配置文件

/etc/nginx/conf.d/ 文件夹下新建 .conf 结尾的文件。

1
vim /etc/nginx/conf.d/speedtest-x.conf

将下面配置复制进去,记得把域名 speedtest.pawswrite.xyz 改成你的域名,有两处:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
server {
listen 80;
listen [::]:80;
server_name speedtest.pawswrite.xyz;

return 301 https://$host$request_uri;
}

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
# Replace bark.app.dev with your real domain name.
server_name speedtest.pawswrite.xyz;

# ssl_certificate /path/to/signed_cert_plus_intermediates;
# ssl_certificate_key /path/to/private_key;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m; # about 40000 sessions
ssl_session_tickets off;

# modern configuration
ssl_protocols TLSv1.3;
ssl_prefer_server_ciphers off;

# HSTS (ngx_http_headers_module is required) (63072000 seconds)
add_header Strict-Transport-Security "max-age=63072000" always;

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;

# verify chain of trust of OCSP response using Root CA and Intermediate certs
# ssl_trusted_certificate /path/to/root_CA_cert_plus_intermediates;

# replace with the IP address of your resolver
#resolver 127.0.0.1;

location / {

log_not_found on;
proxy_pass http://127.0.0.1:9001;

proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;

proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
}
}

测试一下语法是否正确:

1
2
3
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加载配置:

1
systemctl reload nginx

申请证书

安装certbot

看另一篇文章。


用Nginx做简单反向代理
https://pawswrite.xyz/posts/41647.html
作者
Rainbow
发布于
2022年6月3日
许可协议