nginx 配置及注意点

nginx 配置文件如下:

...
#location 1
location / {
    try_files $uri $uri/ =404;
}

#会先到网站根目录下寻找指定的 404 页面, 没有找到就会用 nginx 生成的 404 页
error_page 404 /404.html

#location 2
location ~ \.php$ {
    # try_files $uri =404; 
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index phpinfo.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}
...

访问 http://server_name/xxx.php 时该 xxx.php 是不存在的,以为会出现 nginx 的404 页面,没想到出现的是:
No input file specified.
因为 根据上面的配置,满足了 location 2 的要求,把相关数据传给了 php-fpm,等于是由 php-fpm 处理了。这个报错信息实际上是由 php-fpm 返回的,不会走 error_page 404 /404.html
比较好的改进方法是,在 location 2 中加入try_files $uri =404;,这样文件找不到时能够统一走error_page 404 /404.html
也可以将所有指向不存在的 php 文件的请求都重定向到某个 php 文件:
try_files $uri /index.php

nginx location

语法:

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }

1.nginx 会将 uri 和 prefix location 比较,选中匹配到的长度最长的 prefix location(如果是location ^~ uri格式的,则不进行步骤2)。
2.然后再将 uri 和 正则表达式 location 比较(按照声明的顺序),选中第一个匹配到的 location;如果没有匹配到,则选择步骤1中的 location。

nginx rewirte
ngx_http_rewrite_module 模块用于使用 PCRE 正则表达式更改请求 URI,返回重定向并有条件地选择配置。

该模块上的 breakifreturnrewriteset指令按照如下顺序执行:
- sever 层级的指令按顺序执行。
- 重复:
1.根据请求的 uri 寻找 location
2.在找到的 location 中指令按照顺序执行
3.如果请求的 uri 被重写了,循环将会继续,但是不超过10次。

break
停止处理 ngx_http_rewrite_module 的当前指令集。(循环也会中断)

last
停止处理 ngx_http_rewrite_module 的当前指令集,去匹配新的 location。(类似 continue)

rewrite
语法:rewrite regex replacement [flag]
如果请求 uri 符合正则表达式regex,uri 将会被 replacement 替换。可以使用 flag 来终止指令的后续处理。
如果 replacement 以http://https://$scheme开头,停止后续处理,将重定向返回给客户端。

nginx 内嵌变量

https://nginx.org/en/docs/http/ngx_http_core_module.html#variables


注意点

.
.
.
.
.
附上 nginx 英文文档:https://nginx.org/en/docs/(中文文档翻译不全)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值