我自己的nginx配置

记录自己的nginx配置, 供大家参考. 此配置是包含SSL,HSTS,GZIP,PHP的配置

最新配置文件在此 -> nginx配置HTTPS并取得A+!!

代码

不废话, 直接上代码(详解在这里)!

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
server {
listen 80;
listen [::]:80;
server_name 你的域名;
return 301 https://你的域名$request_uri;
error_page 497 =301 https://你的域名$request_uri;
}

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name 你的域名;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
ssl on;
ssl_certificate 你的网站证书路径;
ssl_certificate_key 你的网站证书密钥路径;
charset utf-8;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

location / {
root 你的网页代码路径;
try_files $uri $uri/ /index.php?/$uri;
index index.php index.html;
}

error_page 404 /404.png;

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root 你的网页代码路径;
}

gzip on;
gzip_min_length 1k;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png image/jpg;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";


location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME 你的网页代码路径/$fastcgi_script_name;
include fastcgi_params;
}

}

详解

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
server {    #服务器针对HTTP连接的措施
listen 80;
listen [::]:80; #IPv6
server_name 你的域名;
return 301 https://你的域名$request_uri; #301跳转到HTTPS页面
error_page 497 =301 https://你的域名$request_uri; #497错误跳转到HTTPS页面
}

server {
listen 443 ssl http2;
listen [::]:443 ssl http2; #IPv6
server_name 你的域名;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"; #HSTS,不想用的请删除这一行
ssl on; #开启SSL
ssl_certificate 你的网站证书路径;
ssl_certificate_key 你的网站证书密钥路径;
charset utf-8; #网页编码设置为UTF-8
access_log /var/log/nginx/access.log; #访问日志
error_log /var/log/nginx/error.log; #错误日志

location / {
root 你的网页代码路径;
try_files $uri $uri/ /index.php?/$uri;
index index.php index.html; #首页代码文件
}

error_page 404 /404.png; #404错误代码文件

gzip on; #GZIP开启状态
gzip_min_length 1k; #GZIP最小压缩文件大小
gzip_comp_level 2; #GZIP压缩等级
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png image/jpg; #GZIP压缩类型
gzip_vary on; #是否缓存GZIP过后的页面/文件
gzip_disable "MSIE [1-6]\."; #由于IE6及以下不支持GZIP,故有此行(即IE6及以下不使用GZIP)


location ~ \.php$ { #PHP的内容
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME 你的网页代码路径/$fastcgi_script_name;
include fastcgi_params;
}

}