常用的 nginx 配置

下面的配置文件加载在 nginx 的配置文件 nginx.conf 里的 http 字段里

1.http 配置

1
server {
2
    listen 80; #监听端口
3
    server_name example.com;  #域名或本地服务器ip
4
      location / {
5
        root   /home/web/dist; #站点静态文件所在目录
6
        index  index.html index.htm; #入口文件
7
8
        #前端history路由支持
9
        try_files $uri $uri/ /index.html;
10
    }
11
}

2.https 配置

1
server {
2
    listen 80;
3
    server_name  example.com;
4
    rewrite ^(.*) https://example.com permanent;
5
}
6
7
server {
8
    listen 443;
9
    server_name  example.com;
10
    ssl on;
11
    ssl_certificate  /etc/nginx/cert/example.com.pem;  #证书pem所在服务器地址
12
    ssl_certificate_key  /etc/nginx/cert/example.com.key; #证书key所在服务器地址
13
    ssl_session_timeout 5m;
14
    ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
15
    ssl_prefer_server_ciphers on;
16
17
    location / {
18
        root /home/web/dist;
19
        index  index.html index.htm;
20
21
          #前端history路由支持
22
        try_files $uri $uri/ /index.html?$query_string;
23
        if (!-e $request_filename){
24
            rewrite ^/(.*) /index.html last;
25
        }
26
        try_files $uri $uri/ /index.html =404;
27
    }
28
29
}

3.同一个域名 http 与 https 两种方式都可访问

1
#核心就是把ssl on;这行注释掉, ssl写在443端口后面, 这样http和https的链接都可以用
2
server {
3
    listen 80;
4
    listen 443 ssl; # ssl写在443端口后面
5
    server_name  example.com;
6
    # ssl on; # 这行注释掉
7
    ssl_certificate  /etc/nginx/cert/1_example.com_bundle.crt;
8
    ssl_certificate_key  /etc/nginx/cert/2_example.com.key;
9
    ssl_session_timeout 5m;
10
    ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
11
    ssl_prefer_server_ciphers on;
12
13
    location / {
14
        root /usr/app/h5;
15
        index  index.html index.htm;
16
          #前端history路由支持
17
        try_files $uri $uri/ /index.html?$query_string;
18
        if (!-e $request_filename){
19
            rewrite ^/(.*) /index.html last;
20
        }
21
22
    }
23
24
}