配置概览
/etc/nginx/nginx.conf
为主配置
在 /etc/nginx/conf.d
为自定义配置
# /etc/nginx/nginx.conf
worker_processes 1;
# events块
events {
woker_connections 1024;
}
http {
# http全局块
# 一些配置
# server块, 用于配置服务器的服务
server {
# 一些配置
}
# 包含的配置文件, 即自定义配置的文件
include /etc/nginx/conf.d/*.conf
}
一般来说, 我们自己添加的配置都放在 /etc/nginx/conf.d
目录中
配置文件以 .conf
结尾
常用到的配置项:
server{
server_name localhost # 域名
listen 80 # 监听的端口号
root /var/www # 网站根目录
# 匹配请求url
location / {
# 一些配置
}
}
location 匹配请求url
匹配 url 类型:
=
精确匹配~
正则匹配~*
正则匹配(忽略大小写)^~
匹配开头字符且忽略以后的字符(前缀匹配)
# "=" 精准匹配, url 必须与表达式完全相同
location = /index { ... }
# "~" 正则匹配(区分大小写), 符合正则表达式
location ~ ^index { ... }
# "~*" 正则表达式(忽略大小写)
# "^~" 前缀匹配
如果不加如何匹配规则时, 默认大小写敏感和前缀匹配
命名匹配, 采用 @
标识, 用于跳转
location /index/ {
# 开始跳转
error_page 404 @index_error;
}
# 跳转的 url
location @index_error { ... }
匹配顺序
=
精准匹配^~
前缀匹配~
正则表达式(区分大小写)~*
正则表达式(忽略大小写)/
任何没有匹配成功的,都会匹配到这里处理
有 "/" 代表目录, 无 "/" 代表文件
配置静态资源
在 server
块中:
# 一个示例
server{
# 其他配置
root /var/www # 配置服务根目录
location / {
index index.html # 路径索引, 通常是网站的入口
}
}
权限
/etc/nginx/nginx.conf
配置用户
user nginx someone;
代理端口
server {
# 忽略域名和端口的相关配置
# 设置匹配规则
location / {
proxy_pass http://127.0.0.1:4567 # 代理的端口
# 设置响应头
proxy_set_header Host $host
proxy_set_header X-Real-Ip $remote_addr
}
}
其它
Typecho 伪静态
server{
# 忽略一些常规配置 ...
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /php根目录$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
}
# 伪静态:
location / {
index index.html index.htm index.php;
try_files $uri $uri/ /index.php$is_args$args;
}
}