Nginx 安装配置


一、下载安装包

http://nginx.org/

二、安装编译工具及库文件

Centos:

yum install -y gcc gcc-c++ glibc make autoconf openssl openssl-devel wget lftp libtool libxslt-devel gd gd-devel pcre pcre-devel zlib zlib-devel geoip geoip-devel

Ubuntu:

apt-get install -y zip libpcre3 libpcre3-dev openssl libssl-dev libxml2 libxml2-dev libxslt-dev libgd-dev libgeoip-dev

useradd -m -d /home/nginx -s /bin/bash nginx

三、安装 Nginx
# tar -zxvf nginx-1.11.10.tar.gz
# cd nginx-1.11.10
# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --http-log-path=/usr/local/nginx/logs/access.log --error-log-path=/usr/local/nginx/logs/error.log --with-file-aio --with-http_ssl_module --with-pcre --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module

安装插件
--add-module=/路径/nginx-goodies-nginx-sticky-module-ng

--with-openssl=/路径/openssl-1.xx

# make&&make install

若make报错则执行

vi  /路径/nginx-goodies-nginx-sticky-module-ng/ngx_http_sticky_module.c

/*if (ngx_http_parse_multi_header_lines(&r->headers_in.cookies, &iphp->sticky_conf->cookie_name, &route) != NGX_DECLINED) {*/
if (ngx_http_parse_multi_header_lines(r, r->headers_in.cookie, &iphp->sticky_conf->cookie_name, &route) != NULL) {

四、Nginx 配置nginx.conf

user nginx nginx;
worker_processes 4;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
}

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;

server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 600;

gzip on;
gzip_min_length 4k;
gzip_buffers 8 1024k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain text/javascript text/css text/xml application/json application/javascript application/x-javascript application/xml;
gzip_vary on;

server_names_hash_bucket_size 2048;
client_header_buffer_size 1024k;
large_client_header_buffers 8 1024k;
client_max_body_size 1024M;
client_header_timeout 300;
client_body_timeout 300;
send_timeout 300;

#用于tomcat反向代理,解决nginx 504错误
proxy_connect_timeout 300; #单位秒
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_buffer_size 1024k;
proxy_buffers 8 1024k;
proxy_busy_buffers_size 2048k;
proxy_temp_file_write_size 2048k;

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 1024k;
fastcgi_buffers 8 1024k;
fastcgi_busy_buffers_size 2048k;
fastcgi_temp_file_write_size 2048k;

#http拒绝服务攻击,限制请求率,限制连接的数量
limit_req_zone $binary_remote_addr zone=one:10m rate=100r/m;
limit_conn_zone $binary_remote_addr zone=addr:10m;

#下面是server虚拟主机的配置,命名和服务器地址根据实际情况修改
upstream backend {
sticky expires=1h domain=xx.xx.com path=/;
#ip_hash;      #同一个IP每次都是请求到固定的后端服务器
# hash        $cookie_jsessionid;
server 192.168.1.1;
server 192.168.1.2;
}

server {
listen 80;
server_name xx.com;

access_log logs/xx.com.access.log;

location / {
root /home/xx;
index index.html index.htm;
autoindex off;
limit_req zone=one burst=20 nodelay;
limit_conn addr 100;
}

location ^~ /(m|api) {
proxy_redirect off;
#获取到的 Host 包含浏览器请求的 IP
proxy_set_header Host $host;
#获取到的 Host 包含浏览器请求的 IP 和端口
#proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
###允许跨域
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
###禁用缓存
proxy_buffering off;

# kill cache
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
#设置反向代理的地址
proxy_pass http://backend/;
}

location ~ .*\.(css|js|html|htm)$ {
root /home/xx;
index index.html index.htm;
try_files $uri $uri/ /m/index.html;
#### kill cache
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
}

#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;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}

# 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;
# }
#}

}

检查配置文件ngnix.conf的正确性命令:
[root@bogon conf]# /usr/local/nginx/sbin/nginx -t

五、启动 Nginx
Nginx 启动命令如下:
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
/usr/local/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/nginx/sbin/nginx -s stop              # 停止 Nginx

nginx针对URL或目录访问控制

根据扩展名限制程序和文件访问
location ~ ^/static/.*.(php|php5|sh|pl|py)$
{
allow 127.0.0.1;
deny all;
}

禁止访问的文件或目录

location ~ ^/(.user.ini|.htaccess|.git|.svn|.project|LICENSE|README.md) {
allow 127.0.0.1;
deny all;
}
禁止访问单个目录
location ~ ^/(static)/ {
allow 127.0.0.1;
deny all;
}
禁止访问多个目录
location ~ ^/(static|js) {
allow 127.0.0.1;
deny all;
}

六、自动启动配置

#!/bin/bash
#
# chkconfig: 2345 90 90
# description: nginxd

nginxd=/usr/local/nginx/sbin/nginx
nginx_config=/usr/local/nginx/conf/nginx.conf
nginx_pid=/var/run/nginx.pid
RETVAL=0
prog="nginx"

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0

# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit 1
fi
echo -n $"Starting $prog: "
daemon $nginxd -c ${nginx_config}
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
return $RETVAL
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
killproc $nginxd
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid
}
# reload nginx service functions.
reload() {
echo -n $"Reloading $prog: "
#kill -HUP `cat ${nginx_pid}`
killproc $nginxd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status|help}"
exit 1
esac
exit $RETVAL
六、配置https
生成证书
可以通过以下步骤生成一个简单的证书:
首先,进入你想创建证书和私钥的目录,例如:

$ cd /usr/local/nginx/conf
创建服务器私钥,命令会让你输入一个口令:

$ openssl genrsa -des3 -out server.key 1024
创建签名请求的证书(CSR):

$ openssl req -new -key server.key -out server.csr
在加载SSL支持的Nginx并使用上述私钥时除去必须的口令:

$ cp server.key server.key.org
$ openssl rsa -in server.key.org -out server.key
配置nginx
最后标记证书使用上述私钥和CSR:

$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
修改Nginx配置文件,让其包含新标记的证书和私钥:

server {
server_name YOUR_DOMAINNAME_HERE;
listen [::]:443 default_server;

ssl_certificate /usr/local/nginx/conf/server.crt;
ssl_certificate_key /usr/local/nginx/conf/server.key;
ssl_session_timeout  5m;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:HIGH:!NULL:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!3DES:!ADH:!PSK:!RC4:!DH:!DHE";
}
重启nginx。
这样就可以通过以下方式访问:

另外还可以加入如下代码实现80端口重定向到443

server {
listen 80;
server_name ww.xxx.com;

rewrite ^(.*)$  https://$host$1 permanent; 

rewrite ^/(.*)$ https://${server_name}$1 permanent;
}

七、跨域设置

说明:一般使用http_origin来进行跨域控制,当不传递origin头的时候,就为这个里面的默认值,当传递有值得时候,才会走下面得正则匹配

map $http_origin $allow_cors {
default 1;
#以下为提供参考的正则表达式
"~^https?://.?.xx.edu.cn.$" 1;
"~^(https?://(www.xx.edu.cn)?)$" 1;
"~http://www.xx.com" 1;
"~*" 0;
}

if ($allow_cors = 0){
return 403;
}

#指定允许其他域名访问
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
#允许的请求类型
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
#许的请求头字段
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";