二、nginx基础配置
(1)错误指向一个页面
http状态指向指定访问页面,在 /etc/nginx/conf.d/default.conf 中配置
error_page 500 502 503 504 /50x.html; error_page 404 /404_error.html;
error_page 403 https://www.cnblogs.com/fange/;
(2)实现访问控制
location / { deny 123.9.51.42; # 表示禁止哪些ip访问 allow 45.76.202.231; # 表示只允许哪些ip访问 deny all; # 禁止所有ip访问 }
需要注意,上述ip地址在匹配时是逐行匹配,一旦匹配到后,下面的将不再执行。
location =/user{ allow all; } location =/admin{ deny all; }
location ~\.php$ { # 不能访问以php结尾的文件
deny all;
}
=表示精准匹配模式,~表示后面跟正则表达式
(3)设置虚拟主机
在 etc/nginx/conf.d/default.conf 中配置
1 server{ 2 listen 8001; 3 server_name localhost; # 此处server_name可直接配置ip地址或域名 4 root /usr/share/nginx/html/html8001; 5 index index.html; 6 }
编写 usr/share/nginx/html/html8001/index.html 中的html代码,使用IP:8001即可访问,(记得访问前重启nginx)
(4)反向代理
server{ listen 80; server_name localhost; location / { proxy_pass https://www.cnblogs.com/fange/;
}
}
反向代理的其他配置项:
proxy_set_header :在将客户端请求发送给后端服务器之前,更改来自客户端的请求头信息。
proxy_connect_timeout:配置Nginx与后端代理服务器尝试建立连接的超时时间。
proxy_read_timeout : 配置Nginx向后端服务器组发出read请求后,等待相应的超时时间。
proxy_send_timeout:配置Nginx向后端服务器组发出write请求后,等待相应的超时时间。
proxy_redirect :用于修改后端服务器返回的响应头中的Location和Refresh。
(5)nginx适配pc及移动端
原理:Nginx通过内置变量$http_user_agent
,可以获取到请求客户端的userAgent,就可以用户目前处于移动端还是PC端,进而展示不同的页面给用户。
操作步骤:
1. 在/usr/share/nginx/目录下新建两个文件夹,分别为:pc和mobile目录。
2. 在pc和miblic目录下,新建两个index.html文件,文件写一些内容。
3. 进入etc/nginx/conf.d
目录下,修改8001.conf文件,改为下面的形式。
server{ listen 80; server_name localhost; location / { root /usr/share/nginx/pc; if ($http_user_agent ~* ‘(Android|webOS|iPhone|iPod|BlackBerry)‘) { root /usr/share/nginx/mobile; } index index.html; } }
(6)gzip配置
配置项:
最简配置:(在主配置文件中配置)
http { gzip on; gzip_types text/plain application/javascript text/css; }
配置后可使用http://tool.chinaz.com/Gzips/Default.aspx工具进行检测。
原文:https://www.cnblogs.com/fange/p/12366220.html