# 静态资源服务器
# 网页服务
server{
listen 80; # 监听端口
server_name localhost; # 域名
location / {
root /app;
try_files $uri $uri/ /index.html; # 单页面应用使用 try_files
index index.html index.htm index.php; # 入口文件
root /usr/local/webserver/nginx/html; # 站点目录,绝对路径
}
location ~* \.(html)$ {
add_header Cache-Control "no-cache, must-revalidate";
}
location ~ .*\.(js|css)?$ {
expires 365d;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
expires 365d;
}
access_log off;
}
# 配置 Gzip
gzip on; # 打开或者关闭gzip压缩的功能
gzip_min_length 1024; # 最小压缩长度, 被压缩的内容超过这个长度才会被压缩,否则直接输出
gzip_comp_level 2; # 压缩级别,分为1-9
# 列出来的内容类型才会被压缩,其他类型的内容不会被压缩,类型指的是MIME类型
gzip_types text/plain application/x-javascript text/css application/xml text/javascript image/jpeg image/gif image/png;
gzip_vary on # 会在响应头增加vary:Accept-Encoding,代表已经进行服务端压缩
gzip_proxine # 设置nginx 服务器是否对后端返回的结果进行gzip压缩,反向代理的时候有效
root /usr/local/test-img;# 存放静态资源的文件路径
# 配置 SSL
nginx -V
# 首先查看是否安装 https_ssl_module
# 如果出现 configure arguments: –with-http_ssl_module, 则已安装
# 准备申请好的SSL证书,丢到cert文件夹下
cd /usr/local/nginx
mkdir cert
server {
listen 443 ssl; # 服务器端口使用443,开启ssl, 这里ssl就是上面安装的ssl模块
server_name www.gausszhou.top; # 域名,多个以空格分开
# ssl证书地址
ssl_certificate /usr/local/nginx/cert/ssl.pem; # pem文件的路径
ssl_certificate_key /usr/local/nginx/cert/ssl.key; # key文件的路径
# ssl验证相关配置
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; #使用服务器端的首选算法
ssl_session_cache shared:SSL:10m;
add_header Strict-Transport-Security "max-age=31536000";
error_page 497 https://$host$request_uri;
location / {
root html;
index index.html index.htm;
}
}
# 配置防盗链
syntax: valid_referers none | blocked | server_names | string...;
default: -
context:server, location
valid_referers blocked server_names ~\.goole\. ~\.baidu\.;
if ($invalid_referer) {
return 403; # 返回403
}
valid_referers blocked server_names ~\.goole\. ~\.baidu\.;
if ($invalid_referer) {
rewrite ^/ http://127.0.0.1:7000/403.png; # 链接到403图片
}
实际配置
location ~ .*\.(jpg|jpeg|gif|png|js|css)$
{
expires 30d;
access_log /dev/null;
valid_referers *.gausszhou.top localhost;
if ($invalid_referer){
return 403;
}
}
# 配置缓存
- 强缓存:Expires,Cache-Control
- 协商缓存:Etag,Last-Modified
强缓存:Expires,Cache-Control
location ~* \.(js|css|gif|jpg|jpeg|png|ico)$ {
expires 1d; # s, m, h, d
add_header Cache-Control public;
}
协商缓存
location ~* \.(html)$ {
add_header Cache-Control no-cache must-revalidate;
}
# 配置 CORS
location ~* /api { {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
}
# 配置访问控制
{
allow 192.168.0.100
deny 192.168.0.101
}
# 配置重定向
举例 将 http 重定向到 https
server {
listen 80;
server_name www.gausszhou.top;
return 301 https://www.gausszhou.top;
}