Nginx安装(CentOS)及常见配置示例

安装Nginx

添加Nginx源

1
rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

查询

1
yum list nginx

安装

1
yum install -y nginx

卸载

1
yum -y remove nginx*

启动

1
service nginx start

停止

1
service nginx stop

设为开机启动

1
chkconfig nginx on

1
systemctl enable nginx.service

查看服务是否开机自启

1
systemctl is-enabled nginx

重新加载配置

1
2
nginx -t
service nginx reload

查看版本

1
nginx -v

配置文件路径/etc/nginx/conf.d

查看Nginx模块

1
nginx -V

Nginx配置生效

查看配置是否可用

1
nginx -t

重新加载配置

1
nginx -s reload

常见场景

WEB容器

HTTP重定向HTTPS

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
server {  
server_name www.psvmc.cn;
listen 80;
# SSL
listen 443 ssl;
ssl_certificate /etc/nginx/cert/xhkjedu.pem;
ssl_certificate_key /etc/nginx/cert/xhkjedu.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

root /data/web_front/myblog/;
index index.html;

# HTTP重定向到HTTPS
if ($scheme = http) {
return 301 https://$host$request_uri;
}

# timeout
keepalive_timeout 60;

# body size
client_max_body_size 200m;

# html不缓存 解决前端更新缓存问题
location ~ .*\.(html)$ {
add_header Cache-Control no-store;
}
}

或者

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
server {  
listen 80;
server_name www.psvmc.cn;
return 301 https://$server_name$request_uri;
}

server {
server_name www.psvmc.cn;

root /data/web_front/myblog/;
index index.html;

# SSL
listen 443 ssl;
ssl_certificate /etc/nginx/cert/xhkjedu.pem;
ssl_certificate_key /etc/nginx/cert/xhkjedu.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

# body size
client_max_body_size 200m;

# log
# error_log /dev/null crit;
error_log /etc/nginx/logs/error_www.psvmc.cn.log error;



# timeout
keepalive_timeout 60;

# html不缓存 解决前端更新缓存问题
location ~ .*\.(html)$ {
add_header Cache-Control no-store;
}
}

静态页面+SSL

文件_school.psvmc.cn.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {  
listen 80;
server_name school.psvmc.cn;
listen 443 ssl;
ssl_certificate /etc/nginx/cert/psvmc.cn.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.cn.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
root /data/web_front/school/;
index index.html;
try_files $uri $uri/ /index.html;
client_max_body_size 200m;
client_body_buffer_size 128k;
send_timeout 60;
}
}

服务器上测试

1
2
curl -H "Host: school.psvmc.cn" http://127.0.0.1
curl -k -H "Host: school.psvmc.cn" https://127.0.0.1

其中:

-k 参数用于忽略自签名证书的验证警告。

SSL核心配置

1
2
3
4
5
6
7
listen 443 ssl;
ssl_certificate /etc/nginx/cert/psvmc.cn.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.cn.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {  
listen 80;
server_name localhost;
index index.html;

location /download/ {
add_header 'Content-Type' 'application/octet-stream';
alias /data/wwwjarapi/schoolfile/static/;
}

location /static/ {
alias /data/wwwjarapi/schoolfile/static/;
}

location / {
root /data/wwwjarapi/schoolfile/static/;
index index.html;
}
}

关键语句

add_header ‘Content-Type’ ‘application/octet-stream’;

Vue history模式

在使用 Vue 的 history 模式时,由于前端路由是通过修改 URL 来实现的,所以在部署到服务器上时,需要进行一些特殊的配置才能确保正常访问。

以下是一个常见的配置流程:

Nginx添加配置:

在 Nginx 的配置文件中,添加一个用于处理前端路由的 location 配置,

如下所示:

1
2
3
location / {
try_files $uri $uri/ /index.html;
}

这个配置将会重定向所有请求到 index.html,这样访问任何一个路由都会返回同一个首页。

然后 Vue Router 会根据 URL 来动态加载相应的组件。

保存并重新启动 Nginx 服务,使配置生效。

禁用缓存

前端项目使用VUE开发的都是单页,也就是只有一个html文件,但是每次更新可能因为用户缓存,而无法正常访问,所以建议html不进行缓存。

如果HTML文件较小建议直接禁用缓存

1
2
3
4
# html不缓存 解决前端更新缓存问题
location ~ .*\.(html)$ {
add_header Cache-Control no-store;
}

如果HTML文件较大建议使用协商方式

1
2
3
4
5
# html协商缓存 解决前端更新缓存问题
location ~ .*\.(html)$ {
# 或者用add_header Cache-Control no-cache;
add_header Pragma no-cache;
}

对比:

Pragma: no-cache:和Cache-Control: no-cache区别

  • Pragma: no-cacheCache-Control: no-cache作用相同

  • Pragma: no-cache可以应用到http 1.0 和http 1.1

  • Cache-Control: no-cache只能应用于http 1.1.

Cache-Control: no-cache和Cache-Control: no-store区别

看字面意思容易误解,no-cache就是不缓存,但是no-cache并不是不缓存,而是使用协商缓存,所以并不能禁止缓存,no-store才是真正的禁止缓存。

从节省带宽角度讲,使用no-cache更优一点,文件未发生改变时只传输很小的报文大小,只有在文件改变时才会传输整个文件大小。而不是no-store不管什么情况都传输整个文件大小。

GZIP压缩

server下添加

1
2
3
4
5
6
7
8
# gzip
gzip on;
gzip_buffers 32 4K;
gzip_comp_level 6;
gzip_min_length 100;
gzip_types application/javascript text/css text/xml;
gzip_disable "MSIE [1-6]\."; #配置禁用gzip条件,支持正则。此处表示ie6及以下不启用gzip(因为ie低版本不支持)
gzip_vary on;

添加日志

1
2
3
4
5
server {  
listen 80;
server_name mapi.psvmc.cn;
error_log /etc/nginx/logs/error_mapi.psvmc.cn.log error;
}

反向代理

反代接口+SSL

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
server {  
listen 80;
server_name mapi.psvmc.cn;
listen 443 ssl;
ssl_certificate /etc/nginx/cert/xhkjedu.pem;
ssl_certificate_key /etc/nginx/cert/xhkjedu.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
error_log /etc/nginx/logs/error_mapi.psvmc.cn.log error;

location / {
client_max_body_size 1000m;
client_body_buffer_size 128k;
client_body_timeout 5m;
send_timeout 20s;

proxy_pass http://127.0.0.1:8080/;
proxy_cookie_path / /;
proxy_redirect / /;
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_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
}

允许跨域

注意:

如果接口本身已经允许跨域了,那么不要配置Nginx,配置后反而会报跨域错误。

示例

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
server {  
listen 80;
server_name aitest.psvmc.cn;

location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header 'Access-Control-Max-Age' 36000;
if ($request_method = OPTIONS ) { return 204; }
client_max_body_size 1000m;
client_body_buffer_size 128k;
client_body_timeout 5m;
send_timeout 20s;
proxy_pass http://127.0.0.1:11434/;
proxy_cookie_path / /;
proxy_redirect / /;
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_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
}

核心配置

1
2
3
4
5
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
add_header 'Access-Control-Max-Age' 36000;
if ($request_method = OPTIONS ) { return 204; }

注意OPTIONS返回200也是可以的,但是返回204会更符合规范。

1
if ($request_method = OPTIONS ) { return 200; }

负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
upstream a_psvmc {  
server 192.168.1.2:8080;
server 192.168.1.3:8080;
ip_hash;
}

server {
listen 80;
server_name a.psvmc.cn;

location / {
proxy_pass http://a_psvmc;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
}
}

反代WS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
upstream wsexam {
server 172.26.69.12:8920;
}


server {
listen 80;
server_name wsexam.psvmc.cn;
client_max_body_size 200m;
location / {
proxy_pass http://wsexam;
proxy_cookie_path / /;
proxy_redirect / /;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

相比之前配置的HTTP代理 主要增加了以下配置

1
2
3
4
5
6
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

反代流式接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {  
listen 80;
server_name aitest.xhkjedu.com;

location / {
proxy_pass http://127.0.0.1:11434/;
# 禁用代理缓冲,确保流式数据传输
proxy_buffering off;
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_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
}

主要配置

proxy_buffering off:对于流式接口,必须将代理缓冲关闭,这样 Nginx 会立即将接收到的数据转发给客户端,而不是先缓存起来,从而保证数据的实时性。

无法获取IP

1
2
3
4
5
6
7
8
9
location /ws/  {
proxy_pass http://127.0.0.1:3000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

注意

只有建立连接的时候才能获取到IP。

获取IP

1
2
3
ws.on('connection', function connection(ws, req) {
const ip = req.connection.remoteAddress;
});

Java

1
2
3
4
String address = session.remoteAddress().toString();
String host = headers.get("Host");
String xrealip = headers.get("X-Real-IP");
String xforwardedfor = headers.get("X-Forwarded-For");

分别取到的地址为

address: 127.0.0.1:48630

host: sockettest2.xhkjedu.com

xrealip: 123.14.108.207

xforwardedfor: 123.14.108.207

其中X-Real-IPX-Forwarded-For获取到的是用户的IP。

大文件上传

添加在server节点下

如果主要处理小文件上传(几十兆以内)

可以参考以下设置:

1
2
3
4
5
6
7
client_max_body_size     50m;
client_header_timeout 10s;
client_body_timeout 30s;
proxy_connect_timeout 10s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
send_timeout 20s;

如果需要支持大文件上传(几百兆甚至上 GB)

可以参考以下设置:

1
2
3
4
5
6
7
client_max_body_size     2000m;
client_header_timeout 15s;
client_body_timeout 300s;
proxy_connect_timeout 30s;
proxy_read_timeout 120s;
proxy_send_timeout 30s;
send_timeout 60s;

每个参数的意思:

client开始的参数是客户端到Nginx的配置

proxy开始的参数是Nginx到反代服务的配置

client_max_body_size

限制请求体的大小,若超过所设定的大小,返回413错误。

client_header_timeout

Nginx 从客户端接收请求头(header)的最大时间。请求头包含了诸如请求方法、请求的 URL、客户端信息等内容。若超时返回408错误。

client_body_timeout

设置读取客户端请求体的超时时间,包括连接建立后读取第一个请求体数据包的超时时间以及两次连续读取请求体数据包之间的超时时间。

在接收到完整的请求头后,Nginx 开始接收请求体。若超时返回413错误。

proxy_connect_timeout

Nginx与上游服务器(被代理的服务器)建立连接所允许的最长时间。默认为60秒,官方推荐最长不要超过75秒。

proxy_read_timeout

Nginx 从上游服务器读取响应数据的最长时间间隔。默认60秒。

proxy_send_timeout

Nginx 向上游服务器发送请求数据的最长时间。默认60秒。

send_timeout

Nginx 向客户端发送响应数据的最长时间间隔。计时起始点是 Nginx 向客户端发送响应数据的第一个字节之后。

注意:

大文件上传费时的是文件到代理服务器(Nginx)的时间,所以proxy_xxx相关的时间不用配置的过长

代理Mysql/远程连接/SSH

详细文章查看:https://www.psvmc.cn/article/2020-12-31-nginx-tcp.html

配置:

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
stream {
upstream ssh {
server 192.168.0.143:22;
}

server {
listen 3333;
proxy_connect_timeout 1h;
proxy_timeout 1h;
proxy_pass ssh;
}

upstream mstsc {
server 192.168.0.19:3389;
}

server {
listen 13389;
proxy_connect_timeout 1h;
proxy_timeout 1h;
proxy_pass mstsc;
}

upstream mysql {
server 192.168.0.143:3306;
}

server {
listen 13306;
proxy_connect_timeout 1h;
proxy_timeout 1h;
proxy_pass mysql;
}
}

注意该配置要和http同级

动静分离

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
upstream filetest_psvmc {   
server 127.0.0.1:8905;
}


server {
listen 80;
server_name filetest.psvmc.cn;
listen 443;
ssl on;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

location ^~ /static/ {
index index.html;
root /data/wwwjarapi/8905xhkjfileapitest/;
}

location / {
client_max_body_size 1000m;
client_body_buffer_size 128k;
client_body_timeout 5m;

proxy_pass http://filetest_psvmc/;
proxy_cookie_path / /;
proxy_redirect / /;
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_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
send_timeout 20s;
}
}

注意

20行的代码root的路径不要配置为/data/wwwjarapi/8905xhkjfileapitest/static/

否则会在static文件夹下再查找static文件夹

正向代理

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
server {
resolver 114.114.114.114;#指定DNS服务器IP地址
listen 1080;
location / {
proxy_pass http://$host$request_uri; #设定代理服务器的协议和地址
proxy_set_header HOST $host;
proxy_buffers 256 4k;
proxy_max_temp_file_size 0k;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_next_upstream error timeout invalid_header http_502;
}
}

server {
resolver 114.114.114.114;#指定DNS服务器IP地址
listen 1443;
location / {
proxy_pass https://$host$request_uri;#设定代理服务器的协议和地址
proxy_buffers 256 4k;
proxy_max_temp_file_size 0k;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_next_upstream error timeout invalid_header http_502;
}
}

测试

1
2
curl  -I --proxy 192.168.10.10:1080 www.baidu.com
curl -I --proxy 192.168.10.10:1443 www.baidu.com

配置项

重定向

GET请求

301重定向

1
2
3
location = /static/应用.apk {
return 301 https://psvmc.oss-cn-huhehaote.aliyuncs.com/client/123.apk;
}

规则路径是可以支持中文的。

重写

主要用于地址迁移 重定向到新的地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {  
server_name zujuan.xhkjedu.com;
client_max_body_size 200m;
listen 443;
ssl on;
ssl_certificate /etc/nginx/cert/xhkjedu.pem;
ssl_certificate_key /etc/nginx/cert/xhkjedu.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
index index.html;
root /data/web_front/zujuan;

location /userapi/login {
rewrite ^/userapi/login$ https://zujuan.xhkjedu.com/userapi/tip.json;
}
}

主要配置是

1
2
3
location /userapi/login {
rewrite ^/userapi/login$ https://zujuan.xhkjedu.com/userapi/tip.json;
}

注意

rewrite是302重定向,会把post请求重定向为get请求。

POST请求

307重定向

  • 301 永久重定向,告诉客户端以后应从新地址访问.
  • 302 作为HTTP1.0的标准,以前叫做Moved Temporarily ,现在叫Found. 现在使用只是为了兼容性的处理,包括PHP的默认Location重定向用的也是302.

但是HTTP 1.1 有303 和307作为详细的补充,其实是对302的细化

  • 303:对于POST请求,它表示请求已经被处理,客户端可以接着使用GET方法去请求Location里的URI。
  • 307:对于POST请求,表示请求还没有被处理,客户端应该向Location里的URI重新发起POST请求。

大部分浏览器 302 会将 POST 请求转为 GET,所以使用307重新发起请求。

1
2
3
location ~ ^/userapi/login {
return 307 https://www.psvmc.cn/sapi/userapi/login;
}

反代

1
2
3
location ~ ^/userapi/login {
proxy_pass https://www.psvmc.cn/sapi/userapi/login;
}

SSL相关

SSL配置

/etc/nginx/cert目录放入证书文件

  • psvmc.pem
  • psvmc.key

Nginx的配置文件添加如下配置

1
2
3
4
5
6
7
8
listen 443;
ssl on;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

配置完成后基本如下

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
upstream test_psvmc {   
server 111.111.111.111:8090;
}


server {
listen 443;
server_name test.psvmc.com;
client_max_body_size 200m;
ssl on;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
proxy_pass https://test_psvmc/;
proxy_cookie_path / /;
proxy_redirect / /;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 200m;
client_body_buffer_size 128k;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
send_timeout 60;
}
}

重启

1
2
nginx -t
service nginx reload

HTTP自动跳转HTTPS

方式1:使用return

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name psvmc.cn;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl;
server_name psvmc.cn;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
# other
}

如果此时nginx作为Tomcat的前端反向代理的话,需要将相应配置放在配置ssl的server块中。

方式2:使用rewrite

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name psvmc.cn;
rewrite ^(.*) https://$server_name$1 permanent;
}

server {
listen 443 ssl;
server_name psvmc.cn;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
# other
}

如果此时nginx作为Tomcat的前端反向代理的话,需要将相应配置放在配置ssl的server块中。

方式3:使用error_page

只允许HTTP来访问时,用HTTP访问会让Nginx报497错误,然后利用error_page将链接重定向至HTTPS上。

1
2
3
4
5
6
7
8
9
server {
listen 80;
listen 443 ssl;
server_name psvmc.cn;
ssl_certificate /etc/nginx/cert/psvmc.pem;
ssl_certificate_key /etc/nginx/cert/psvmc.key;
# other
error_page 497 https://$server_name$request_uri;
}

使用error_page指令时,将http和https的监听配置写在同一个server块中,对应的其他配置也需要在该server配置块中完成。

需要注意的是,此时需要将error_page指令语句写在最后,否则不能生效。

日志

默认位置

使用yum安装的Nginx的默认日志位置

1
cd /var/log/nginx

示例

创建文件夹

1
mkdir /etc/nginx/logs/

项目对应的配置文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
server_name psvmc.cn www.psvmc.cn;

location / {
root /data/www/www;
index index.html index.htm;
}

access_log /etc/nginx/logs/access_www.psvmc.cn.log buffer=32k flush= 5s;
error_log /etc/nginx/logs/error_www.psvmc.cn.log error;
log_not_found off;
}

错误日志

1
error_log  <FILE>  <LEVEL>;

关键字:其中关键字error_log不能改变

日志文件:可以指定任意存放日志的目录

错误日志级别:常见的错误日志级别有[debug | info | notice | warn | error | crit | alert | emerg],级别越高记录的信息越少。

生产场景一般是 warn | error | crit 这三个级别之一

关闭错误日志

只禁用无法找到的错误日志

1
log_not_found off;

禁用所有错误日志

error_log off并不能关闭日志记录功能,它将日志文件写入一个文件名为off的文件中,如果你想关闭错误日志记录功能,应使用以下配置:

把存储位置设置到Linux的黑洞中去

1
error_log /dev/null crit;

访问日志

默认

1
2
3
4
5
6
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
}

其中main是定义日志格式化方式的名称log_format main

关闭访问日志

1
access_log  off;

location

基本语法

1
location [=|~|~*|^~|@] pattern{……}

规则

  • = 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
  • ~ 匹配区分大小写的定的正则表达式
  • ~* 匹配不区分大小写的定的正则表达式
  • ^~ 类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,
    那么就停止搜索其他模式了
  • !~ 不匹配区分大小写的定的正则表达式
  • !~* 不匹配不区分大小写的定的正则表达式

示例

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
location = / {
# 只匹配 / 的查询.
[ configuration A ]
}

location / {
# 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。
[ configuration B ]
}

location ^~ /images/ {
# 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。
[ configuration C ]
}

location ~* \.(gif|jpg|jpeg)$ {
# 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处理。
[ configuration D ]
}

location ~*.(gif|jpg|swf)$ {
valid_referers none blocked image.psvmc.cn static.psvmc.cn;
if ($invalid_referer) {
#防盗链
rewrite ^/ http://$host/daolian.png;
}
[ configuration E ]
}

各请求的处理如下例:

  • / → configuration A
  • /documents/document.html → configuration B
  • /images/1.gif → configuration C
  • /documents/1.jpg → configuration D

生效顺序

模式 含义
location = /uri = 表示精确匹配,只有完全匹配上才能生效
location ^~ /uri ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location ~ pattern 开头表示区分大小写的正则匹配
location ~* pattern 开头表示不区分大小写的正则匹配
location /uri 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location / 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default

优先级

  1. 精确匹配 =
  2. 前缀匹配 ^~
  3. 按文件中从前到后顺序的正则匹配
  4. 匹配不带任何修饰的前缀匹配
  5. 交给/通用匹配
  6. 当有匹配成功时候,停止匹配,按当前匹配规则处理请求

如果相同的路由,后者覆盖前者

1
2
3
4
5
6
location /download/ {
alias /data/path1/;
}
location /download/ {
alias /data/path2/;
}

这个生效的就是/data/path2/

root、alias指令区别

1
2
3
4
5
6
7
8
9
location /img/ {
alias /var/www/image/;
}
#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件

location /img/ {
root /var/www/image;
}
#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。]

区别

  • alias是一个目录别名的定义,root则是最上层目录的定义。
  • alias后面必须要用/结束,否则会找不到文件的 而root则可有可无

常见错误

端口无法绑定

nginx: [emerg] bind() to 0.0.0.0:8091 failed (13: Permission denied)

是开启selinux 导致的

查看状态 如果输出 disabledPermissive 那就是关闭了
如果输出 Enforcing 那就是开启了 selinux

1
getenforce

临时关闭

1
2
3
4
# 临时关闭
setenforce 0
# 临时开启
setenforce 1

永久关闭

修改/etc/selinux/config文件

1
vi /etc/selinux/config

1
SELINUX=enforcing

改为

1
SELINUX=disabled

立即生效

1
source /etc/selinux/config

静态项目访问403

编辑配置文件

1
vi /etc/nginx/nginx.conf

修改内容

用户修改为root 默认是nginx

1
user root;

输入

1
getenforce

出现Enforcing表示已强制执行安全策略了

配置关闭

1
vi /etc/selinux/config

修改为disable

SELINUX=disabled

重启

1
reboot

正向代理和反向代理

  • 正向代理:客户端知晓目标服务器,客户端借助代理服务器来访问目标服务器。

    此时,目标服务器不清楚真正的客户端是谁,仅知道代理服务器。

    正向代理主要为客户端服务,常用于突破访问限制、隐藏客户端 IP 地址等场景。

    例如,在国内通过代理服务器访问被限制的国外网站。

  • 反向代理:客户端并不了解目标服务器的具体信息,只知道反向代理服务器。

    客户端的请求发送到反向代理服务器,由反向代理服务器将请求转发给内部的目标服务器,再把目标服务器的响应返回给客户端。

    反向代理主要为服务器端服务,常用于负载均衡、隐藏服务器 IP 地址、提高安全性等场景。

全局变量

全局变量

  • $args : 这个变量等于请求行中的参数,同$query_string
  • $content_length : 请求头中的Content-length字段。
  • $content_type : 请求头中的Content-Type字段。
  • $document_root : 当前请求在root指令中指定的值。
  • $host : 请求主机头字段,否则为服务器名称。
  • $http_user_agent : 客户端agent信息
  • $http_cookie : 客户端cookie信息
  • $limit_rate : 这个变量可以限制连接速率。
  • $request_method : 客户端请求的动作,通常为GET或POST。
  • $remote_addr : 客户端的IP地址。
  • $remote_port : 客户端的端口。
  • $remote_user : 已经经过Auth Basic Module验证的用户名。
  • $request_filename : 当前请求的文件路径,由root或alias指令与URI请求生成。
  • $scheme : HTTP方法(如http,https)。
  • $server_protocol : 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
  • $server_addr : 服务器地址,在完成一次系统调用后可以确定这个值。
  • $server_name : 服务器名称。
  • $server_port : 请求到达服务器的端口号。
  • $request_uri : 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。
  • $uri : 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。
  • $document_uri : 与$uri相同。

例:

http://localhost:88/test1/test2/test.php

1
2
3
4
5
6
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

localhost和127.0.0.1

添加配置

1
2
cd /etc/nginx/conf.d/
vi _localhost_80.conf

内容

1
2
3
4
5
6
server {  
listen 80;
server_name localhost;
index index.html;
root /data/wwwjarapi/schoolfile/static;
}

重启Nginx

1
systemctl restart nginx

查看是否生效

1
lsof -i:80

访问测试

1
2
3
curl http://127.0.0.1/test.txt
curl http://172.26.69.13/test.txt
curl http://localhost/test.txt

结果

使用127.0.0.1的时候可以访问前两种方式。

使用localhost的时候三种方式都能访问。