实用必备!Nginx五大应用场景全解析
时间:2026-09-20 09:51 来源:未知 人气:
一、HTTP服务器
Nginx本身也是一个静态资源的服务器,当只有静态资源的时候,就可以使用Nginx来做服务器,如果一个网站只是静态页面的话,那么就可以通过这种方式来实现部署。
1、 首先在文档根目录Docroot(/usr/local/var/www)下创建html目录, 然后在html中放一个test.html;
图片
2、 配置nginx.conf中的server;
user mengday staff;
http {
server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
# 默认location
location / {
root /usr/local/var/www/html;
index index.html index.htm;
}
}
}
3、访问测试;
- http://localhost/指向/usr/local/var/www/index.html, index.html是安装nginx自带的html
- http://localhost/test.html指向/usr/local/var/www/html/test.html
注意:如果访问图片出现403 Forbidden错误,可能是因为nginx.conf 的第一行user配置不对,默认是#user nobody;是注释的,linux下改成user root; macos下改成user 用户名 所在组; 然后重新加载配置文件或者重启,再试一下就可以了, 用户名可以通过who am i 命令来查看。
4、指令简介;
- server : 用于定义服务,http中可以有多个server块。
- listen : 指定服务器侦听请求的IP地址和端口,如果省略地址,服务器将侦听所有地址,如果省略端口,则使用标准端口。
- server_name : 服务名称,用于配置域名。
- location : 用于配置映射路径uri对应的配置,一个server中可以有多个location, location后面跟一个uri,可以是一个正则表达式, / 表示匹配任意路径, 当客户端访问的路径满足这个uri时就会执行location块里面的代码。
- root : 根路径,当访问http://localhost/test.html,“/test.html”会匹配到”/”uri, 找到root为/usr/local/var/www/html,用户访问的资源物理地址=root + uri = /usr/local/var/www/html + /test.html=/usr/local/var/www/html/test.html。
- index : 设置首页,当只访问server_name时后面不跟任何路径是不走root直接走index指令的;如果访问路径中没有指定具体的文件,则返回index设置的资源,如果访问http://localhost/html/则默认返回index.html。
5、location uri正则表达式;