Linux环境 nginx安装与配置
一、安装nginx
- 检查是否已安装nginx
- 命令行执行
nginx -v
查看是否有nginx环境变量
2) 执行
whereis nginx
查看是否有nginx文件,确认没有进行第二步
- 安装nginx
yum install nginx
在出现提示,输入y,回车
Total download size: 680 k
Installed size: 1.8 M
Is this ok [y/N]: y
等待一会就安装成功。
然后再执行
[root@ ~]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/share/nginx /usr/share/man/man3/nginx.3pm.gz /usr/share/man/man8/nginx.8.gz
默认nginx的配置在/etc/nginx文件夹下,nginx的静态文件在/usr/share/nginx/html文件夹下。
二、nginx 命令
-
查看nginx帮助文档
nginx -h
2)启动nginx
nginx
3)关闭nginx
nginx -s stop
4)检查nginx配置
nginx -t
5)重启nginx
nginx -s reload -
开启自启
systemctl enable nginx
三、配置nginx
-
开启文件压缩和文件缓存
a) 在/etc/nginx/nginx.conf文件的http模块下添加开启gzip
gzip on;
启用gzip压缩的最小文件;小于设置值的文件将不会被压缩
gzip_min_length 1k;
gzip 压缩级别 1-10
gzip_comp_level 2;
进行压缩的文件类型。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
etag协商缓存 默认是开启的
etag on;
b) 在配置文件的server模块的location模块下添加
# 添加响应头,no-cache:协商缓存,no-store:不缓存
add_header Cache-Control max-age=no-cache; -
如果遇到http 413 Request Body Too Large 错误,在nginx.conf文件的http模块下添加
client_max_body_size 20M; #(配置请求体缓存区大小)
client_body_buffer_size 256k; #(设置客户端请求体最大值)
fastcgi_intercept_errors on; -
遇到http 400 Too Large,在server模块下配置
请求行+请求头的标准大小为1k
client_header_buffer_size 1k;
请求行+请求头的最大大小为2k
large_client_header_buffers 4 8k;
-
解决「could not build the server_names_hash」问题,在nginx.conf文件的http模块添加
server_names_hash_bucket_size 64; # 或 128 -
location rewrite 转发不到?参数。在转发的URL后加“?”即可。
rewrite partten /url? last;
四、一个较完整的server的方向代理及负载均衡的配置。
upstream sitdemo.example.com {
server ip:port;
}
server {
listen 80;
server_name sitdemo.example.com;
root /usr/share/nginx/html/demo;
# 请求行+请求头的标准大小为1k
client_header_buffer_size 1k;
# 请求行+请求头的最大大小为2k
large_client_header_buffers 2 1k;
#add_header Access-Control-Allow-Origin *;
#add_header Access-Control-Allow-Headers *;
#add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
# 执行日志目录及格式
#access_log /var/log/nginx/oauth/access.log main;
location /fauth {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite ^/fauth/(.*)$ /$1 break;
proxy_pass http://sitdemo.example.com;
}
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://sitdemo.example.com;
}
location = / {
rewrite ^/$ /view last;
}
location ^~ /view {
# 添加响应头,no-cache:协商缓存,no-store:不缓存
add_header Cache-Control max-age=no-cache;
try_files $uri $uri/ /view/index.html;
}
}