目录
- Nginx 项目必配
- 1.禁止ip地址访问,只允许域名访问
- 1.1 接收到ip访问或者指定域名访问时,返回500错误
- 1.2 可以将流量集中导入到自己的网站,只要做一下跳转设置就可以
- 2.Include 包含文件
- 3.alias与root路径匹配(虚拟目录)
- 4.error_page 自定义报错提示信息
- 5.Try_file路径匹配,按顺序交叉文件是否存在
Nginx 项目必配
1.禁止ip地址访问,只允许域名访问
1.1 接收到ip访问或者指定域名访问时,返回500错误
server {
listen 80;
server_name www.oldboy.com
}
server {
listen 80 default_server; #默认有优先返回
server_name _; #空主机头或者ip
return 500; #返回500错误
}
1.2 可以将流量集中导入到自己的网站,只要做一下跳转设置就可以
server {
listen 80 default_server;
return 302 https://www.oldboy.com;
}
2.Include 包含文件
一台服务器配置多个server网站,会导致nginx.conf主配置文件变得非常庞大而且可读性非常差。使用Include的是为了简化主配置文件。
3.alias与root路径匹配(虚拟目录)
alias是一个目录别名定义,root则是最上层目录定义
root配置实例
#用户访问image/db.jpg,实际上会上/code/image目录下区找db.jpg
location /image/ {
root /code;
}
ls /code/image/1.png
http://yan.test.com/image/1.png
alias配置实例:
#用户访问image/db.jpg,实际上会上/code/目录下区找
location /image/ {
alias /code/;
}
ls /code/1.png
http://yan.test.com/image/1.png
4.error_page 自定义报错提示信息
server {
listen 80;
server_name yan.test.com;
location / {
root /html/tes2t; //模拟404报错
index index.html;
proxy_pass http://1.1.1.1 //模拟500报错
}
error_page 404 /404.jpg; //指定error404报错文件
error_page 500 502 503 504 /500.png;
location = /404.jpg { //通过location指定404报错页面路径
root /etc/nginx/error;
}
location = /500.png {
root /etc/nginx/error;
}
5.Try_file路径匹配,按顺序交叉文件是否存在
location / {
try_file $uri $uri/ /index.php;
}
#1.检查用户请求的uri内容是否在本地,存在则解析
#2.将请求加/,类似于重定向处理
#3.最后交给index.php处理
1.演示环境准备
[root@nginx-web02 ~]# echo "try_page" > /soft/code/index.html
echo "tomcat_Page" > /soft/app/apache-tomcat-9.0.12/webapps/Root/index.html
#启动tomcat
[root@nginx-web02 ~]# sh ../startup.sh
#检查tomcat端口
[root@nginx-web02 ~]# netstat -lnpt | grep “8080”
2.配置web的tryfiles
server {
listen 80;
server_name yan.test.com;
root /soft/code/;
index index.html;
location / {
try_files $uri @java_page;
}
location @java_page {
proxy_pass http://127.0.0.1:8080;
}
systemctl restart nginx
3.测试
默认访问结果:
[root@nginx-web02 html]# curl http://yan.test.com/
tomcat_Page //因为$uri匹配域名后面输入的呢容,所以当直接访问http://yan.test.com
[root@nginx-web02 html]# curl http://yan.test.com/index.html
try_page //因为$uri匹配域名后面输入的呢容,所以当直接访问http://yan.test.com/index.html,$uri匹配/index.html,跳转到/soft/code/index.html
#将/soft/code/index.html文件删除
rm -rf /soft/code/index.html
#发现由tomcat吐回请求
[root@nginx-web02 test]# curl http://yan.test.com
tomcat_tr