Nginx的安装、配置、优化
nginx
安装
安装依赖
yum -y install make zlib zlib-devel gcc gcc-c++ libtool openssl openssl-devel pcre pcre-devel
下载解压
编译
./configure --user=www --group=www --prefix=/usr/local/nginx \
--with-mail_ssl_module --with-http_stub_status_module \
--with-http_ssl_module --with-http_v2_module \
--with-http_gzip_static_module --with-http_sub_module \
--with-http_realip_module \
--with-threads --with-stream
make && make install
文件夹
conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。
html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。
sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。
配置说明
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
ss;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
return 301 https://$server_name$request_uri;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
upstream backend {
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
}
# HTTPS server
server {
listen 443 ssl;
server_name localhost;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
}
location匹配规则
location [ 空格 | = | ~ | ~* | !~ | !~* | @ ] /uri/ {}
- = :精确匹配
- :正则匹配,区分大小写匹配
~* :正则匹配,不区分大小写匹配
!~ : 区分大小写不匹配
!~* : 不区分大小写不匹配
^~ : 匹配普通字符串(前缀匹配),如果匹配成功不再匹配其他location
@ :指定一个命名的location,用于内部重定向请求
/ : 通用匹配
匹配顺序:
- = 精确匹配
- 字符串匹配(长>短),遇到
^~
匹配停止匹配 - 正则匹配(上>下)
- 通用匹配,普通字符串前缀匹配
正则匹配
、精确匹配
需要注意path末尾的 /
eg:
# 精确匹配
location = /abcd {}
# 正则匹配区分大小写
location ~ \.php(.*)$ {
root /var/www/web/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_read_timeout 300;
}
root && alias 区别
- 映射方式不同;root+location;alias会替换掉location
alias
结尾必须用/
结束