神刀安全网

本博客 Nginx 配置之完整篇

文章目录

最近有很多朋友邮件或者留言询问本博客服务端配置相关问题,基本都是关于 HTTPS 和 HTTP/2 的,其实我的 Nginx 配置在之前的文章中多次提到过,不过都比较分散。为了方便大家参考,本文贴出完整配置。

本文内容会随时调整或更新,请大家不要把本文内容全文转载到第三方平台,以免给他人造成困扰或误导。另外限于篇幅,本文不会对配置做过多说明,如有疑问或不同意见,欢迎留言指出。

准备工作

我的 VPS 系统是 Ubuntu 14.04.3 LTS,如果你使用的是其它发行版,与包管理有关的命令请自行调整。

本博客是我的试验田,Nginx 自然要用最新的 1.9.12。为了启用 Certificate Transparency,我使用了 nginx-ct 这个模块。同时,我还使用了 CloudFlare Patch 过的 OpenSSL 1.0.2g 做为 Nginx 的 SSL 库。下面是完整安装过程:

首先安装 Nginx 依赖库:

sudo apt-get install build-essential libpcre3 libpcre3-dev zlib1g-de 

然后获取 OpenSSL 源码和 Patch、最新的 Nginx 以及 nginx-ct 源码,开始编译:

git clone https://github.com/cloudflare/sslconfig wget -O openssl.zip -c https://github.com/openssl/openssl/archive/OpenSSL_1_0_2g.zip unzip openssl.zip mv openssl-OpenSSL_1_0_2g/ openssl cd openssl && patch -p1 < ../sslconfig/patches/openssl__chacha20_poly1305_draft_and_rfc_ossl102g.patch   cd ../  wget -c http://nginx.org/download/nginx-1.9.12.tar.gz tar zxf nginx-1.9.12.tar.gz  wget -O nginx-ct.zip -c https://github.com/grahamedgecombe/nginx-ct/archive/v1.0.0.zip unzip nginx-ct.zip  cd nginx-1.9.12/  ./configure --add-module=../nginx-ct-1.0.0 --with-openssl=../openssl --with-http_v2_module --with-http_ssl_module make sudo make install 

Nginx 默认装在 /usr/local/nginx/ 目录,如果需要更改路径可以在 configure 时指定。

为了方便管理 Nginx 服务,再创建一个管理脚本:

sudo vim /etc/init.d/nginx 

输入以下内容:

#! /bin/sh  ### BEGIN INIT INFO # Provides:          nginx # Required-Start:    $all # Required-Stop:     $all # Default-Start:     2 3 4 5 # Default-Stop:      0 1 6 # Short-Description: starts the nginx web server # Description:       starts nginx using start-stop-daemon ### END INIT INFO  PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DAEMON=/usr/local/nginx/sbin/nginx NAME=nginx DESC=nginx  test -x $DAEMON || exit 0  # Include nginx defaults if available if [ -f /etc/default/nginx ] ; then     . /etc/default/nginx fi  set -e  . /lib/lsb/init-functions  case "$1" in   start)     echo -n "Starting $DESC: "     start-stop-daemon --start --quiet --pidfile /usr/local/nginx/logs/$NAME.pid /         --exec $DAEMON -- $DAEMON_OPTS || true     echo "$NAME."     ;;   stop)     echo -n "Stopping $DESC: "     start-stop-daemon --stop --quiet --pidfile /usr/local/nginx/logs/$NAME.pid /         --exec $DAEMON || true     echo "$NAME."     ;;   restart|force-reload)     echo -n "Restarting $DESC: "     start-stop-daemon --stop --quiet --pidfile /         /usr/local/nginx/logs/$NAME.pid --exec $DAEMON || true     sleep 1     start-stop-daemon --start --quiet --pidfile /         /usr/local/nginx/logs/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS || true     echo "$NAME."     ;;   reload)       echo -n "Reloading $DESC configuration: "       start-stop-daemon --stop --signal HUP --quiet --pidfile /usr/local/nginx/logs/$NAME.pid /           --exec $DAEMON || true       echo "$NAME."       ;;   status)       status_of_proc -p /usr/local/nginx/logs/$NAME.pid "$DAEMON" nginx && exit 0 || exit $?       ;;   *)     N=/etc/init.d/$NAME     echo "Usage: $N {start|stop|restart|reload|force-reload|status}" >&2     exit 1     ;; esac  exit 0 

增加执行权限:

sudo chmod a+x /etc/init.d/nginx 

现在管理 Nginx 只需使用以下命令即可:

sudo service nginx start|stop|restart|reload 

如果要开机自动启动 Nginx,请执行以下命令:

sudo update-rc.d -f nginx defaults 

到此为止,Nginx 已经安装完毕。再来修改一下它的全局配置,打开 /usr/local/nginx/conf/nginx.conf ,新增或修改以下内容:

http {     sendfile           on;     tcp_nopush         on;     tcp_nodelay        on;      keepalive_timeout  60;      #... ...#      gzip               on;     gzip_vary          on;      gzip_comp_level    6;     gzip_buffers       16 8k;      gzip_min_length    1000;     gzip_proxied       any;     gzip_disable       "msie6";      gzip_http_version  1.0;      gzip_types         text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;      #... ...#      include /home/jerry/www/nginx_conf/*.conf; } 

最后的 include 用来加载我个人目录下的配置文件,这样今后创建和修改站点配置就不需要再使用 sudo 权限了。

要想在浏览器中启用 HTTP/2 就必须部署 HTTPS,要部署 HTTPS 就必须有合法的证书。本博客目前在用 RapidSSL 的单域名证书,在 NameCheap 买的。另外,我还申请了 Let’s Encrypt 的免费证书备用。一般情况下,个人使用 Let’s Encrypt 的免费证书就足够了,还可以节省一笔开销。

要申请 Let’s Encrypt 证书,推荐使用 Neilpang/le 这个小巧无依赖的命令行工具,或者参考我的这篇文章: Let’s Encrypt,免费好用的 HTTPS 证书

站点配置

以下是本博客站点完整配置:

server {     server_name          www.imququ.com imququ.com;     server_tokens        off;      listen               443 ssl http2 fastopen=3 reuseport;      keepalive_timeout    75s;      include              /home/jerry/www/nginx_conf/ip.blacklist;      ssl_ct               on;     ssl_ct_static_scts   /home/jerry/www/scts;      ssl_certificate      /home/jerry/www/ssl/chained.pem;     ssl_certificate_key  /home/jerry/www/ssl/domain.key;      ssl_dhparam          /home/jerry/www/ssl/dhparams.pem;      ssl_ciphers                EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;     ssl_prefer_server_ciphers  on;      ssl_protocols              TLSv1 TLSv1.1 TLSv1.2;      ssl_session_cache          shared:SSL:50m;     ssl_session_timeout        1d;      ssl_session_tickets        on;     ssl_session_ticket_key     /home/jerry/www/ssl/session_ticket.key;      ssl_stapling               on;     ssl_stapling_verify        on;     ssl_trusted_certificate    /home/jerry/www/ssl/full_chained.pem;      resolver                   114.114.114.114 valid=300s;     resolver_timeout           10s;      access_log                 /home/jerry/www/nginx_log/imququ_com.log;      if ($request_method !~ ^(GET|HEAD|POST|OPTIONS)$ ) {         return    444;     }      if ($host != 'imququ.com' ) {         rewrite   ^/(.*)$  https://imququ.com/$1 permanent;     }      location ~* (robots/.txt|favicon/.ico|crossdomain/.xml|google4c90d18e696bdcf8/.html|BingSiteAuth/.xml)$ {         root          /home/jerry/www/imququ.com/www/static;         expires       max;     }      location ~ ^/static/uploads/ {         root          /home/jerry/www/imququ.com/www;         add_header    Access-Control-Allow-Origin *;          set           $expires_time max;          valid_referers blocked none server_names *.qgy18.com *.inoreader.com feedly.com *.feedly.com www.udpwork.com theoldreader.com digg.com *.feiworks.com *.newszeit.com r.mail.qq.com yuedu.163.com;         if ($invalid_referer) {             set       $expires_time -1;             rewrite   ^/ /static/img/blog/403.png redirect;         }          expires       $expires_time;     }      location ~ ^/static/ {         root          /home/jerry/www/imququ.com/www;         add_header    Access-Control-Allow-Origin *;               expires       max;     }      location ~ ^/admin {         proxy_http_version       1.1;          add_header               Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";         add_header               X-Frame-Options deny;         add_header               X-Content-Type-Options nosniff;          proxy_set_header         X-Via            QingDao.Aliyun;         proxy_set_header         Connection       "";         proxy_set_header         Host             imququ.com;         proxy_set_header         X-Real_IP        $remote_addr;         proxy_set_header         X-Forwarded-For  $proxy_add_x_forwarded_for;          proxy_pass               http://127.0.0.1:9095;     }      location / {         proxy_http_version       1.1;          add_header               Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";         add_header               X-Frame-Options deny;         add_header               X-Content-Type-Options nosniff;         add_header               Content-Security-Policy "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' blob: https:; img-src data: https: http://ip.qgy18.com:81; style-src 'unsafe-inline' https:; child-src https:; connect-src 'self' https://translate.googleapis.com; frame-src https://disqus.com https://www.slideshare.net";         add_header               Public-Key-Pins 'pin-sha256="aef6IF2UF6jNEwA2pNmP7kpgT6NFSdt7Tqf5HzaIGWI="; pin-sha256="YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg="; max-age=2592000; includeSubDomains';         add_header               Cache-Control no-cache;          proxy_ignore_headers     Set-Cookie;          proxy_hide_header        Vary;         proxy_hide_header        X-Powered-By;          proxy_set_header         X-Via            QingDao.Aliyun;         proxy_set_header         Connection       "";         proxy_set_header         Host             imququ.com;         proxy_set_header         X-Real_IP        $remote_addr;         proxy_set_header         X-Forwarded-For  $proxy_add_x_forwarded_for;          proxy_pass               http://127.0.0.1:9095;     } }  server {     server_name    www.imququ.com imququ.com;     server_tokens  off;      access_log     /dev/null;      if ($request_method !~ ^(GET|HEAD|POST)$ ) {         return  444;     }      location ^~ /.well-known/acme-challenge/ {         alias /home/jerry/www/challenges/;         try_files $uri =404;     }      location / {         rewrite ^/(.*)$ https://imququ.com/$1 permanent;     } } 

以上配置中的一些关键点分散在我之前的这些文章中:

一切妥当后,推荐使用以下两个在线服务来检测站点 HTTPS 配置:

1)Qualys SSL Labs’s SSL Server Test

测试地址: https://www.ssllabs.com/ssltest/index.html ,以下是本博客测试结果截图:

本博客 Nginx 配置之完整篇 查看完整测试结果 »

2)HTTP Security Report

测试地址: https://httpsecurityreport.com/ ,以下是本博客测试结果截图:

本博客 Nginx 配置之完整篇 查看完整测试结果 »

本文链接: 参与评论

EOF

发表于 2016-03-21 23:35:32 ,并被添加「QuQuBlog、Nginx」标签。

本站所有文章均为本人原创,如果你认为我的文章对你有帮助,欢迎捐赠本站。详情请点这里 »

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » 本博客 Nginx 配置之完整篇

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮