文章目录
启动nginx
# 启动
systemctl restart nginx;
# 报错了,查看报错信息
systemctl status nginx;
错误提示为这两句:
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx[5640]: nginx: [emerg] still could not bind()
很明显,80端口被占用了。 是https服务占用的。
# 查看端口
netstat -nltp | grep 80;
# kill掉pid
kill -9 555;
# 再次查看
netstat -nltp | grep 80;
# 发现没有杀掉,用systemctl停掉
systemctl stop https;
systemctl restart nginx; 不报错说明启动成功。
浏览器输如网址,看到nginx界面。
搭建静态服务器
创建目录:
mkdir -p /www/static ;
cd /www/static;
vim index.html; 输入如下内容:
<html lang="zh">
<body>
welcome
</body>
</html>
配置/etc/nginx/nginx.conf ,修改server模块:
server {
listen 80 ;
server_name 47.104.176.200;
root /www/static-web;
index index.html index.htm;
location / {
root /www/static-web;
}
}
重启nginx 。
浏览器访问服务器地址,显示welcome说明成功。
报错 nginx: [emerg] invalid parameter “localhost” in /etc/nginx/nginx.conf:39
说明配置不对。
元素
搭建静态服务器主要用到http和server等。
server
upstream
翻译 是 上游 的意思。 感觉很抽象。
他的作用是设置一组服务器,可以在代理的时候调用,并且有负载均衡的作用。
listen
Syntax: 太多,略
Default: listen *:80 | *:8000;
Context: server # 上下文是server,上级是server
设置IP的地址和端口,或服务器接受请求的UNIX域套接字的路径。可以同时指定地址和端口,或者只能指定地址或端口。地址也可以是主机名,例如:
# 可以多行共同起作用
listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;
ip6地址用方括号括起来:
listen [::]:8000;
listen [::1];
UNIX域套接字使用“UNIX:”前缀指定:
listen unix:/var/run/nginx.sock;
location
localtion是非常重要的模块。顾名思义,它的作用是定位。
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
= 精确匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
~ 为区分大小写匹配(可用正则表达式)
~* 为不区分大小写匹配(可用正则表达式)
^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。
例如:
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
The “/” 匹配 configuration A,
the “/index.html” 匹配 configuration B,
the “/documents/document.html” 匹配 configuration C,
the “/images/1.gif” 匹配 configuration D,
and the “/documents/1.jpg” 匹配 configuration E.
root 和alias
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
root 会返回 root+ 请求地址。
alias会返回 root+ 不含路径的请求地址,因为alias会把location后面配置的路径丢弃掉。
例如请求为 /api/index.html
location ^~ /api/ {
root /www/root/html/;
}
返回: /www/root/html/api/index.html
location ^~ /api/ {
alias /www/root/html/new_api/;
}
返回: /www/root/html/new_api/index.html # 这里没有加 /api/ 这个路径。
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。
注:
1. 使用alias时,目录名后面一定要加"/"。
3. alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
4. alias只能位于location块中。(root可以不放在location中)
location ~*.(gif|jpg|swf)$ { } 是什么意思
这种写法见的最多
~* 表示匹配模式是 不区分大小写,正则匹配
匹配规则是后缀匹配 以.fig、.jpg、.swf 结尾的 多个表达式用 | 表示,其实就是正则表达式。
default_server 和default
default_server 用来设置默认服务器。
当请求中的host找不到匹配时,就会到default_server, default_server找不到,就到host,如果还找不到,就404。
其他
官网文档(不太容易看懂):
http://nginx.org/en/docs/