針對nginx應用場景的配置 知識整理

本文爲轉載,原文連接
javascript

前言

本來想寫整理一篇針對nginx應用場景的相應配置,但發現已經有人整理了,並且寫得很是不錯,特地轉過來php

概論

Nginx 是一款面向性能設計的 HTTP 服務器,能反向代理 HTTP,HTTPS 和郵件相關(SMTP,POP3,IMAP)的協議連接。而且提供了負載均衡以及 HTTP 緩存。它的設計充分使用異步事件模型,削減上下文調度的開銷,提升服務器併發能力。採用了模塊化設計,提供了豐富模塊的第三方模塊。css

因此關於 Nginx,有這些標籤:「異步」「事件」「模塊化」「高性能」「高併發」「反向代理」「負載均衡」html

Linux系統:Centos 7 x64 Nginx版本:1.11.5前端

目錄

安裝

安裝依賴

prce(重定向支持)和openssl(https支持,若是不須要https能夠不安裝。)java

yum install -y pcre-devel 
yum -y install gcc make gcc-c++ wget
yum -y install openssl openssl-devel 

CentOS 6.5 我安裝的時候是選擇的「基本服務器」,默認這兩個包都沒安裝全,因此這兩個都運行安裝便可。node

下載

nginx的全部版本在這裏python

wget http://nginx.org/download/nginx-1.13.3.tar.gz
wget http://nginx.org/download/nginx-1.13.7.tar.gz

# 若是沒有安裝wget
# 下載已編譯版本
$ yum install wget

# 解壓壓縮包
tar zxf nginx-1.13.3.tar.gz

編譯安裝

而後進入目錄編譯安裝,configure參數說明linux

cd nginx-1.11.5
./configure

....
Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

安裝報錯誤的話好比:「C compiler cc is not found」,這個就是缺乏編譯環境,安裝一下就能夠了 yum -y install gcc make gcc-c++ openssl-develnginx

若是沒有error信息,就能夠執行下邊的安裝了:

make
make install

nginx測試

運行下面命令會出現兩個結果,通常狀況nginx會安裝在/usr/local/nginx目錄中

cd /usr/local/nginx/sbin/
./nginx -t

# nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

設置全局nginx命令

vi ~/.bash_profile

將下面內容添加到 ~/.bash_profile 文件中

PATH=$PATH:$HOME/bin:/usr/local/nginx/sbin/
export PATH

運行命令 source ~/.bash_profile 讓配置當即生效。你就能夠全局運行 nginx 命令了。

Mac 安裝

Mac OSX 安裝特別簡單,首先你須要安裝 Brew, 經過 brew 快速安裝 nginx

安裝nginx

brew install nginx
# Updating Homebrew...
# ==> Auto-updated Homebrew!
# Updated 2 taps (homebrew/core, homebrew/cask).
# ==> Updated Formulae
# ==> Installing dependencies for nginx: openssl, pcre
# ==> Installing nginx dependency: openssl
# ==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2o_1.high_sierra.bottle.tar.gz
# ######################################################################## 100.0%
# ==> Pouring openssl-1.0.2o_1.high_sierra.bottle.tar.gz
# ==> Caveats
# A CA file has been bootstrapped using certificates from the SystemRoots
# keychain. To add additional certificates (e.g. the certificates added in
# the System keychain), place .pem files in
#   /usr/local/etc/openssl/certs
# 
# and run
#   /usr/local/opt/openssl/bin/c_rehash
# 
# This formula is keg-only, which means it was not symlinked into /usr/local,
# because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.
# 
# If you need to have this software first in your PATH run:
#   echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.zshrc
# 
# For compilers to find this software you may need to set:
#     LDFLAGS:  -L/usr/local/opt/openssl/lib
#     CPPFLAGS: -I/usr/local/opt/openssl/include
# For pkg-config to find this software you may need to set:
#     PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig
# 
# ==> Summary
# 🍺  /usr/local/Cellar/openssl/1.0.2o_1: 1,791 files, 12.3MB
# ==> Installing nginx dependency: pcre
# ==> Downloading https://homebrew.bintray.com/bottles/pcre-8.42.high_sierra.bottle.tar.gz
# ######################################################################## 100.0%
# ==> Pouring pcre-8.42.high_sierra.bottle.tar.gz
# 🍺  /usr/local/Cellar/pcre/8.42: 204 files, 5.3MB
# ==> Installing nginx
# ==> Downloading https://homebrew.bintray.com/bottles/nginx-1.13.12.high_sierra.bottle.tar.gz
# ######################################################################## 100.0%
# ==> Pouring nginx-1.13.12.high_sierra.bottle.tar.gz
# ==> Caveats
# Docroot is: /usr/local/var/www
# 
# The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
# nginx can run without sudo.
# 
# nginx will load all files in /usr/local/etc/nginx/servers/.
# 
# To have launchd start nginx now and restart at login:
#   brew services start nginx
# Or, if you don't wacd /usr/local/Cellar/nginx/1.13.12/n just run:
# cd /usr/local/Cellar/nginx/1.13.12/

啓動服務

注意默認端口不是 8080 查看確認端口是否被佔用。

brew services start nginx
# http://localhost:8080/

開機自啓動

開機自啓動方法一:

編輯 vi /lib/systemd/system/nginx.service 文件,沒有建立一個 touch nginx.service 而後將以下內容根據具體狀況進行修改後,添加到nginx.service文件中:

[Unit]
Description=nginx
After=network.target remote-fs.target nss-lookup.target

[Service]

Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • [Unit]:服務的說明
  • Description:描述服務
  • After:描述服務類別
  • [Service]服務運行參數的設置
  • Type=forking是後臺運行的形式
  • ExecStart爲服務的具體運行命令
  • ExecReload爲重啓命令
  • ExecStop爲中止命令
  • PrivateTmp=True表示給服務分配獨立的臨時空間

注意:[Service]的啓動、重啓、中止命令所有要求使用絕對路徑。

[Install]運行級別下服務安裝的相關設置,可設置爲多用戶,即系統運行級別爲3

保存退出。

設置開機啓動,使配置生效:

# 啓動nginx服務
systemctl start nginx.service
# 中止開機自啓動
systemctl disable nginx.service
# 查看服務當前狀態
systemctl status nginx.service
# 查看全部已啓動的服務
systemctl list-units --type=service
# 從新啓動服務
systemctl restart nginx.service
# 設置開機自啓動
systemctl enable nginx.service
# 輸出下面內容表示成功了
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
systemctl is-enabled servicename.service # 查詢服務是否開機啓動
systemctl enable *.service # 開機運行服務
systemctl disable *.service # 取消開機運行
systemctl start *.service # 啓動服務
systemctl stop *.service # 中止服務
systemctl restart *.service # 重啓服務
systemctl reload *.service # 從新加載服務配置文件
systemctl status *.service # 查詢服務運行狀態
systemctl --failed # 顯示啓動失敗的服務

注:*表明某個服務的名字,如http的服務名爲httpd

開機自啓動方法二:

vi /etc/rc.local

# 在 rc.local 文件中,添加下面這條命令
/usr/local/nginx/sbin/nginx start

若是開機後發現自啓動腳本沒有執行,你要去確認一下rc.local這個文件的訪問權限是不是可執行的,由於rc.local默認是不可執行的。修改rc.local訪問權限,增長可執行權限:

# /etc/rc.local是/etc/rc.d/rc.local的軟鏈接,
chmod +x /etc/rc.d/rc.local

官方腳本 ed Hat NGINX Init Script

運維

服務管理

# 啓動
/usr/local/nginx/sbin/nginx

# 重啓
/usr/local/nginx/sbin/nginx -s reload

# 關閉進程
/usr/local/nginx/sbin/nginx -s stop

# 平滑關閉nginx
/usr/local/nginx/sbin/nginx -s quit

# 查看nginx的安裝狀態,
/usr/local/nginx/sbin/nginx -V 

關閉防火牆,或者添加防火牆規則就能夠測試了

service iptables stop

或者編輯配置文件:

vi /etc/sysconfig/iptables

添加這樣一條開放80端口的規則後保存:

-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

重啓服務便可:

service iptables restart
# 命令進行查看目前nat
iptables -t nat -L

重啓服務防火牆報錯解決

service iptables restart
# Redirecting to /bin/systemctl restart  iptables.service
# Failed to restart iptables.service: Unit iptables.service failed to load: No such file or directory.

在CentOS 7或RHEL 7或Fedora中防火牆由 firewalld 來管理,固然你能夠還原傳統的管理方式。或則使用新的命令進行管理。 假如採用傳統請執行一下命令:

# 傳統命令
systemctl stop firewalld
systemctl mask firewalld
# 安裝命令
yum install iptables-services

systemctl enable iptables 
service iptables restart

nginx卸載

若是經過yum安裝,使用下面命令安裝。

yum remove nginx

編譯安裝,刪除/usr/local/nginx目錄便可 若是配置了自啓動腳本,也須要刪除。

參數說明

參數 說明
--prefix=<path> Nginx安裝路徑。若是沒有指定,默認爲 /usr/local/nginx。
--sbin-path=<path> Nginx可執行文件安裝路徑。只能安裝時指定,若是沒有指定,默認爲<prefix>/sbin/nginx。
--conf-path=<path> 在沒有給定-c選項下默認的nginx.conf的路徑。若是沒有指定,默認爲<prefix>/conf/nginx.conf。
--pid-path=<path> 在nginx.conf中沒有指定pid指令的狀況下,默認的nginx.pid的路徑。若是沒有指定,默認爲 <prefix>/logs/nginx.pid。
--lock-path=<path> nginx.lock文件的路徑。
--error-log-path=<path> 在nginx.conf中沒有指定error_log指令的狀況下,默認的錯誤日誌的路徑。若是沒有指定,默認爲 <prefix>/- logs/error.log。
--http-log-path=<path> 在nginx.conf中沒有指定access_log指令的狀況下,默認的訪問日誌的路徑。若是沒有指定,默認爲 <prefix>/- logs/access.log。
--user=<user> 在nginx.conf中沒有指定user指令的狀況下,默認的nginx使用的用戶。若是沒有指定,默認爲 nobody。
--group=<group> 在nginx.conf中沒有指定user指令的狀況下,默認的nginx使用的組。若是沒有指定,默認爲 nobody。
--builddir=DIR 指定編譯的目錄
--with-rtsig_module 啓用 rtsig 模塊
--with-select_module --without-select_module 容許或不容許開啓SELECT模式,若是 configure 沒有找到更合適的模式,好比:kqueue(sun os),epoll (linux kenel 2.6+), rtsig(- 實時信號)或者/dev/poll(一種相似select的模式,底層實現與SELECT基本相 同,都是採用輪訓方法) SELECT模式將是默認安裝模式
--with-poll_module --without-poll_module Whether or not to enable the poll module. This module is enabled by, default if a more suitable method such as kqueue, epoll, rtsig or /dev/poll is not discovered by configure.
--with-http_ssl_module Enable ngx_http_ssl_module. Enables SSL support and the ability to handle HTTPS requests. Requires OpenSSL. On Debian, this is libssl-dev. 開啓HTTP SSL模塊,使NGINX能夠支持HTTPS請求。這個模塊須要已經安裝了OPENSSL,在DEBIAN上是libssl
--with-http_realip_module 啓用 ngx_http_realip_module
--with-http_addition_module 啓用 ngx_http_addition_module
--with-http_sub_module 啓用 ngx_http_sub_module
--with-http_dav_module 啓用 ngx_http_dav_module
--with-http_flv_module 啓用 ngx_http_flv_module
--with-http_stub_status_module 啓用 "server status" 頁
--without-http_charset_module 禁用 ngx_http_charset_module
--without-http_gzip_module 禁用 ngx_http_gzip_module. 若是啓用,須要 zlib 。
--without-http_ssi_module 禁用 ngx_http_ssi_module
--without-http_userid_module 禁用 ngx_http_userid_module
--without-http_access_module 禁用 ngx_http_access_module
--without-http_auth_basic_module 禁用 ngx_http_auth_basic_module
--without-http_autoindex_module 禁用 ngx_http_autoindex_module
--without-http_geo_module 禁用 ngx_http_geo_module
--without-http_map_module 禁用 ngx_http_map_module
--without-http_referer_module 禁用 ngx_http_referer_module
--without-http_rewrite_module 禁用 ngx_http_rewrite_module. 若是啓用須要 PCRE 。
--without-http_proxy_module 禁用 ngx_http_proxy_module
--without-http_fastcgi_module 禁用 ngx_http_fastcgi_module
--without-http_memcached_module 禁用 ngx_http_memcached_module
--without-http_limit_zone_module 禁用 ngx_http_limit_zone_module
--without-http_empty_gif_module 禁用 ngx_http_empty_gif_module
--without-http_browser_module 禁用 ngx_http_browser_module
--without-http_upstream_ip_hash_module 禁用 ngx_http_upstream_ip_hash_module
--with-http_perl_module 啓用 ngx_http_perl_module
--with-perl_modules_path=PATH 指定 perl 模塊的路徑
--with-perl=PATH 指定 perl 執行文件的路徑
--http-log-path=PATH Set path to the http access log
--http-client-body-temp-path=PATH Set path to the http client request body temporary files
--http-proxy-temp-path=PATH Set path to the http proxy temporary files
--http-fastcgi-temp-path=PATH Set path to the http fastcgi temporary files
--without-http 禁用 HTTP server
--with-mail 啓用 IMAP4/POP3/SMTP 代理模塊
--with-mail_ssl_module 啓用 ngx_mail_ssl_module
--with-cc=PATH 指定 C 編譯器的路徑
--with-cpp=PATH 指定 C 預處理器的路徑
--with-cc-opt=OPTIONS Additional parameters which will be added to the variable CFLAGS. With the use of the system library PCRE in FreeBSD, it is necessary to indicate --with-cc-opt="-I /usr/local/include". If we are using select() and it is necessary to increase the number of file descriptors, then this also can be assigned here: --with-cc-opt="-D FD_SETSIZE=2048".
--with-ld-opt=OPTIONS Additional parameters passed to the linker. With the use of the system library PCRE in - FreeBSD, it is necessary to indicate --with-ld-opt="-L /usr/local/lib".
--with-cpu-opt=CPU 爲特定的 CPU 編譯,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
--without-pcre 禁止 PCRE 庫的使用。同時也會禁止 HTTP rewrite 模塊。在 "location" 配置指令中的正則表達式也須要 PCRE 。
--with-pcre=DIR 指定 PCRE 庫的源代碼的路徑。
--with-pcre-opt=OPTIONS Set additional options for PCRE building.
--with-md5=DIR Set path to md5 library sources.
--with-md5-opt=OPTIONS Set additional options for md5 building.
--with-md5-asm Use md5 assembler sources.
--with-sha1=DIR Set path to sha1 library sources.
--with-sha1-opt=OPTIONS Set additional options for sha1 building.
--with-sha1-asm Use sha1 assembler sources.
--with-zlib=DIR Set path to zlib library sources.
--with-zlib-opt=OPTIONS Set additional options for zlib building.
--with-zlib-asm=CPU Use zlib assembler sources optimized for specified CPU, valid values are: pentium, pentiumpro
--with-openssl=DIR Set path to OpenSSL library sources
--with-openssl-opt=OPTIONS Set additional options for OpenSSL building
--with-debug 啓用調試日誌
--add-module=PATH Add in a third-party module found in directory PATH

配置

在Centos 默認配置文件在 /usr/local/nginx-1.5.1/conf/nginx.conf 咱們要在這裏配置一些文件。nginx.conf是主配置文件,由若干個部分組成,每一個大括號{}表示一個部分。每一行指令都由分號結束;,標誌着一行的結束。

經常使用正則

正則 說明 正則 說明
. 匹配除換行符之外的任意字符 $ 匹配字符串的結束
? 重複0次或1次 {n} 重複n次
+ 重複1次或更屢次 {n,} 重複n次或更屢次
* 重複0次或更屢次 [c] 匹配單個字符c
\d 匹配數字 [a-z] 匹配a-z小寫字母的任意一個
^ 匹配字符串的開始 - -

全局變量

變量 說明 變量 說明
$args 這個變量等於請求行中的參數,同$query_string $remote_port 客戶端的端口。
$content_length 請求頭中的Content-length字段。 $remote_user 已經通過Auth Basic Module驗證的用戶名。
$content_type 請求頭中的Content-Type字段。 $request_filename 當前請求的文件路徑,由root或alias指令與URI請求生成。
$document_root 當前請求在root指令中指定的值。 $scheme HTTP方法(如http,https)。
$host 請求主機頭字段,不然爲服務器名稱。 $server_protocol 請求使用的協議,一般是HTTP/1.0或HTTP/1.1。
$http_user_agent 客戶端agent信息 $server_addr 服務器地址,在完成一次系統調用後能夠肯定這個值。
$http_cookie 客戶端cookie信息 $server_name 服務器名稱。
$limit_rate 這個變量能夠限制鏈接速率。 $server_port 請求到達服務器的端口號。
$request_method 客戶端請求的動做,一般爲GET或POST。 $request_uri 包含請求參數的原始URI,不包含主機名,如:/foo/bar.php?arg=baz。
$remote_addr 客戶端的IP地址。 $uri 不帶請求參數的當前URI,$uri不包含主機名,如/foo/bar.html。
$document_uri 與$uri相同。 - -

例如請求:http://localhost:3000/test1/test2/test.php

$host:localhost
$server_port:3000
$request_uri:/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

符號參考

符號 說明 符號 說明 符號 說明
k,K 千字節 m,M 兆字節 ms 毫秒
s m 分鐘 h 小時
d w M 一個月, 30天

例如,"8k","1m" 表明字節數計量。
例如,"1h 30m","1y 6M"。表明 "1小時 30分","1年零6個月"。

配置文件

nginx 的配置系統由一個主配置文件和其餘一些輔助的配置文件構成。這些配置文件均是純文本文件,所有位於 nginx 安裝目錄下的 conf 目錄下。

指令由 nginx 的各個模塊提供,不一樣的模塊會提供不一樣的指令來實現配置。 指令除了 Key-Value 的形式,還有做用域指令。

nginx.conf 中的配置信息,根據其邏輯上的意義,對它們進行了分類,也就是分紅了多個做用域,或者稱之爲配置指令上下文。不一樣的做用域含有一個或者多個配置項。

下面的這些上下文指令是用的比較多:

Directive Description Contains Directive
main nginx 在運行時與具體業務功能(好比 http 服務或者 email 服務代理)無關的一些參數,好比工做進程數,運行的身份等。 user, worker_processes, error_log, events, http, mail
http 與提供 http 服務相關的一些配置參數。例如:是否使用 keepalive 啊,是否使用 gzip 進行壓縮等。 server
server http 服務上支持若干虛擬主機。每一個虛擬主機一個對應的 server 配置項,配置項裏面包含該虛擬主機相關的配置。在提供 mail 服務的代理時,也能夠創建若干 server. 每一個 server 經過監聽的地址來區分。 listen, server_name, access_log, location, protocol, proxy, smtp_auth, xclient
location http 服務中,某些特定的 URL 對應的一系列配置項。 index, root
mail 實現 email 相關的 SMTP/IMAP/POP3 代理時,共享的一些配置項(由於可能實現多個代理,工做在多個監聽地址上)。 server, http, imap_capabilities
include 以便加強配置文件的可讀性,使得部分配置文件能夠從新使用。 -
valid_referers 用來校驗Http請求頭Referer是否有效。 -
try_files 用在server部分,不過最多見的仍是用在location部分,它會按照給定的參數順序進行嘗試,第一個被匹配到的將會被使用。 -
if 當在location塊中使用if指令,在某些狀況下它並不按照預期運行,通常來講避免使用if指令。 -

例如咱們再 nginx.conf 裏面引用兩個配置 vhost/example.com.conf 和 vhost/gitlab.com.conf 它們都被放在一個我本身新建的目錄 vhost 下面。nginx.conf 配置以下:

worker_processes  1;
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;

    #gzip  on;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    include  vhost/example.com.conf;
    include  vhost/gitlab.com.conf;
}

簡單的配置: example.com.conf

server {
    #偵聽的80端口
    listen       80;
    server_name  baidu.com app.baidu.com; # 這裏指定域名
    index        index.html index.htm;    # 這裏指定默認入口頁面
    root /home/www/app.baidu.com;         # 這裏指定目錄
}

內置預約義變量

Nginx提供了許多預約義的變量,也能夠經過使用set來設置變量。你能夠在if中使用預約義變量,也能夠將它們傳遞給代理服務器。如下是一些常見的預約義變量,更多詳見

變量名稱
$args_name 在請求中的name參數
$args 全部請求參數
$query_string $args的別名
$content_length 請求頭Content-Length的值
$content_type 請求頭Content-Type的值
$host 若是當前有Host,則爲請求頭Host的值;若是沒有這個頭,那麼該值等於匹配該請求的server_name的值
$remote_addr 客戶端的IP地址
$request 完整的請求,從客戶端收到,包括Http請求方法、URI、Http協議、頭、請求體
$request_uri 完整請求的URI,從客戶端來的請求,包括參數
$scheme 當前請求的協議
$uri 當前請求的標準化URI

反向代理

反向代理是一個Web服務器,它接受客戶端的鏈接請求,而後將請求轉發給上游服務器,並將從服務器獲得的結果返回給鏈接的客戶端。下面簡單的反向代理的例子:

server {  
  listen       80;                                                        
  server_name  localhost;                                              
  client_max_body_size 1024M;  # 容許客戶端請求的最大單文件字節數

  location / {
    proxy_pass                         http://localhost:8080;
    proxy_set_header Host              $host:$server_port;
    proxy_set_header X-Forwarded-For   $remote_addr; # HTTP的請求端真實的IP
    proxy_set_header X-Forwarded-Proto $scheme;      # 爲了正確地識別實際用戶發出的協議是 http 仍是 https
  }
}

複雜的配置: gitlab.com.conf。

server {
    #偵聽的80端口
    listen       80;
    server_name  git.example.cn;
    location / {
        proxy_pass   http://localhost:3000;
        #如下是一些反向代理的配置可刪除
        proxy_redirect             off;
        #後端的Web服務器能夠經過X-Forwarded-For獲取用戶真實IP
        proxy_set_header           Host $host;
        client_max_body_size       10m; #容許客戶端請求的最大單文件字節數
        client_body_buffer_size    128k; #緩衝區代理緩衝用戶端請求的最大字節數
        proxy_connect_timeout      300; #nginx跟後端服務器鏈接超時時間(代理鏈接超時)
        proxy_send_timeout         300; #後端服務器數據回傳時間(代理髮送超時)
        proxy_read_timeout         300; #鏈接成功後,後端服務器響應時間(代理接收超時)
        proxy_buffer_size          4k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
        proxy_buffers              4 32k; #proxy_buffers緩衝區,網頁平均在32k如下的話,這樣設置
        proxy_busy_buffers_size    64k; #高負荷下緩衝大小(proxy_buffers*2)
    }
}

代理到上游服務器的配置中,最重要的是proxy_pass指令。如下是代理模塊中的一些經常使用指令:

指令 說明
proxy_connect_timeout Nginx從接受請求至鏈接到上游服務器的最長等待時間
proxy_send_timeout 後端服務器數據回傳時間(代理髮送超時)
proxy_read_timeout 鏈接成功後,後端服務器響應時間(代理接收超時)
proxy_cookie_domain 替代從上游服務器來的Set-Cookie頭的domain屬性
proxy_cookie_path 替代從上游服務器來的Set-Cookie頭的path屬性
proxy_buffer_size 設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
proxy_buffers proxy_buffers緩衝區,網頁平均在多少k如下
proxy_set_header 重寫發送到上游服務器頭的內容,也能夠經過將某個頭部的值設置爲空字符串,而不發送某個頭部的方法實現
proxy_ignore_headers 這個指令禁止處理來自代理服務器的應答。
proxy_intercept_errors 使nginx阻止HTTP應答代碼爲400或者更高的應答。

負載均衡

upstream指令啓用一個新的配置區段,在該區段定義一組上游服務器。這些服務器可能被設置不一樣的權重,也可能出於對服務器進行維護,標記爲down。

upstream gitlab {
    ip_hash;
    # upstream的負載均衡,weight是權重,能夠根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的概率越大。
    server 192.168.122.11:8081 ;
    server 127.0.0.1:82 weight=3;
    server 127.0.0.1:83 weight=3 down;
    server 127.0.0.1:84 weight=3; max_fails=3  fail_timeout=20s;
    server 127.0.0.1:85 weight=4;;
    keepalive 32;
}
server {
    #偵聽的80端口
    listen       80;
    server_name  git.example.cn;
    location / {
        proxy_pass   http://gitlab;    #在這裏設置一個代理,和upstream的名字同樣
        #如下是一些反向代理的配置可刪除
        proxy_redirect             off;
        #後端的Web服務器能夠經過X-Forwarded-For獲取用戶真實IP
        proxy_set_header           Host $host;
        proxy_set_header           X-Real-IP $remote_addr;
        proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;
        client_max_body_size       10m;  #容許客戶端請求的最大單文件字節數
        client_body_buffer_size    128k; #緩衝區代理緩衝用戶端請求的最大字節數
        proxy_connect_timeout      300;  #nginx跟後端服務器鏈接超時時間(代理鏈接超時)
        proxy_send_timeout         300;  #後端服務器數據回傳時間(代理髮送超時)
        proxy_read_timeout         300;  #鏈接成功後,後端服務器響應時間(代理接收超時)
        proxy_buffer_size          4k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
        proxy_buffers              4 32k;# 緩衝區,網頁平均在32k如下的話,這樣設置
        proxy_busy_buffers_size    64k; #高負荷下緩衝大小(proxy_buffers*2)
        proxy_temp_file_write_size 64k; #設定緩存文件夾大小,大於這個值,將從upstream服務器傳
    }
}

每一個請求按時間順序逐一分配到不一樣的後端服務器,若是後端服務器down掉,能自動剔除。

負載均衡:

upstream模塊可以使用3種負載均衡算法:輪詢、IP哈希、最少鏈接數。

輪詢: 默認狀況下使用輪詢算法,不須要配置指令來激活它,它是基於在隊列中誰是下一個的原理確保訪問均勻地分佈到每一個上游服務器;
IP哈希: 經過ip_hash指令來激活,Nginx經過IPv4地址的前3個字節或者整個IPv6地址做爲哈希鍵來實現,同一個IP地址老是能被映射到同一個上游服務器;
最少鏈接數: 經過least_conn指令來激活,該算法經過選擇一個活躍數最少的上游服務器進行鏈接。若是上游服務器處理能力不一樣,能夠經過給server配置weight權重來講明,該算法將考慮到不一樣服務器的加權最少鏈接數。

RR

簡單配置 ,這裏我配置了2臺服務器,固然其實是一臺,只是端口不同而已,而8081的服務器是不存在的,也就是說訪問不到,可是咱們訪問 http://localhost 的時候,也不會有問題,會默認跳轉到http://localhost:8080具體是由於Nginx會自動判斷服務器的狀態,若是服務器處於不能訪問(服務器掛了),就不會跳轉到這臺服務器,因此也避免了一臺服務器掛了影響使用的狀況,因爲Nginx默認是RR策略,因此咱們不須要其餘更多的設置

upstream test {
    server localhost:8080;
    server localhost:8081;
}
server {
    listen       81;
    server_name  localhost;
    client_max_body_size 1024M;
 
    location / {
        proxy_pass http://test;
        proxy_set_header Host $host:$server_port;
    }
}

負載均衡的核心代碼爲

upstream test {
    server localhost:8080;
    server localhost:8081;
}

權重

指定輪詢概率,weight和訪問比率成正比,用於後端服務器性能不均的狀況。 例如

upstream test {
    server localhost:8080 weight=9;
    server localhost:8081 weight=1;
}

那麼10次通常只會有1次會訪問到8081,而有9次會訪問到8080

ip_hash

上面的2種方式都有一個問題,那就是下一個請求來的時候請求可能分發到另一個服務器,當咱們的程序不是無狀態的時候(採用了session保存數據),這時候就有一個很大的很問題了,好比把登陸信息保存到了session中,那麼跳轉到另一臺服務器的時候就須要從新登陸了,因此不少時候咱們須要一個客戶只訪問一個服務器,那麼就須要用iphash了,iphash的每一個請求按訪問ip的hash結果分配,這樣每一個訪客固定訪問一個後端服務器,能夠解決session的問題。

upstream test {
    ip_hash;
    server localhost:8080;
    server localhost:8081;
}

fair

這是個第三方模塊,按後端服務器的響應時間來分配請求,響應時間短的優先分配。

upstream backend {
    fair;
    server localhost:8080;
    server localhost:8081;
}

url_hash

這是個第三方模塊,按訪問url的hash結果來分配請求,使每一個url定向到同一個後端服務器,後端服務器爲緩存時比較有效。 在upstream中加入hash語句,server語句中不能寫入weight等其餘的參數,hash_method是使用的hash算法

upstream backend {
    hash $request_uri;
    hash_method crc32;
    server localhost:8080;
    server localhost:8081;
}

以上5種負載均衡各自適用不一樣狀況下使用,因此能夠根據實際狀況選擇使用哪一種策略模式,不過fair和url_hash須要安裝第三方模塊才能使用

server指令可選參數:

  1. weight:設置一個服務器的訪問權重,數值越高,收到的請求也越多;
  2. fail_timeout:在這個指定的時間內服務器必須提供響應,若是在這個時間內沒有收到響應,那麼服務器將會被標記爲down狀態;
  3. max_fails:設置在fail_timeout時間以內嘗試對一個服務器鏈接的最大次數,若是超過這個次數,那麼服務器將會被標記爲down;
  4. down:標記一個服務器再也不接受任何請求;
  5. backup:一旦其餘服務器宕機,那麼有該標記的機器將會接收請求。

keepalive指令:

Nginx服務器將會爲每個worker進行保持同上遊服務器的鏈接。

屏蔽ip

在nginx的配置文件nginx.conf中加入以下配置,能夠放到http, server, location, limit_except語句塊,須要注意相對路徑,本例當中nginx.confblocksip.conf在同一個目錄中。

include blockip.conf;

在blockip.conf裏面輸入內容,如:

deny 165.91.122.67;

deny IP;   # 屏蔽單個ip訪問
allow IP;  # 容許單個ip訪問
deny all;  # 屏蔽全部ip訪問
allow all; # 容許全部ip訪問
deny 123.0.0.0/8   # 屏蔽整個段即從123.0.0.1到123.255.255.254訪問的命令
deny 124.45.0.0/16 # 屏蔽IP段即從123.45.0.1到123.45.255.254訪問的命令
deny 123.45.6.0/24 # 屏蔽IP段即從123.45.6.1到123.45.6.254訪問的命令

# 若是你想實現這樣的應用,除了幾個IP外,其餘所有拒絕
allow 1.1.1.1; 
allow 1.1.1.2;
deny all; 

第三方模塊安裝方法

./configure --prefix=/你的安裝目錄  --add-module=/第三方模塊目錄

重定向

  • permanent 永久性重定向。請求日誌中的狀態碼爲301
  • redirect 臨時重定向。請求日誌中的狀態碼爲302

重定向整個網站

server {
    server_name old-site.com
    return 301 $scheme://new-site.com$request_uri;
}

重定向單頁

server {
    location = /oldpage.html {
        return 301 http://example.org/newpage.html;
    }
}

重定向整個子路徑

location /old-site {
    rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;
}

性能

內容緩存

容許瀏覽器基本上永久地緩存靜態內容。 Nginx將爲您設置Expires和Cache-Control頭信息。

location /static {
    root /data;
    expires max;
}

若是要求瀏覽器永遠不會緩存響應(例如用於跟蹤請求),請使用-1。

location = /empty.gif {
    empty_gif;
    expires -1;
}

Gzip壓縮

gzip  on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
gzip_types
    text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
    text/javascript application/javascript application/x-javascript
    text/x-json application/json application/x-web-app-manifest+json
    text/css text/plain text/x-component
    font/opentype application/x-font-ttf application/vnd.ms-fontobject
    image/x-icon;
gzip_disable  "msie6";

打開文件緩存

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

SSL緩存

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

上游Keepalive

upstream backend {
    server 127.0.0.1:8080;
    keepalive 32;
}
server {
    ...
    location /api/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

監控

使用ngxtop實時解析nginx訪問日誌,而且將處理結果輸出到終端,功能相似於系統命令top。全部示例都讀取nginx配置文件的訪問日誌位置和格式。若是要指定訪問日誌文件和/或日誌格式,請使用-f和-a選項。

注意:在nginx配置中/usr/local/nginx/conf/nginx.conf日誌文件必須是絕對路徑。

# 安裝 ngxtop
pip install ngxtop

# 實時狀態
ngxtop
# 狀態爲404的前10個請求的路徑:
ngxtop top request_path --filter 'status == 404'

# 發送總字節數最多的前10個請求
ngxtop --order-by 'avg(bytes_sent) * count'

# 排名前十位的IP,例如,誰攻擊你最多
ngxtop --group-by remote_addr

# 打印具備4xx或5xx狀態的請求,以及status和http referer
ngxtop -i 'status >= 400' print request status http_referer

# 由200個請求路徑響應發送的平均正文字節以'foo'開始:
ngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith("foo")'

# 使用「common」日誌格式從遠程機器分析apache訪問日誌
ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common

常見使用場景

跨域問題

在工做中,有時候會遇到一些接口不支持跨域,這時候能夠簡單的添加add_headers來支持cors跨域。配置以下:

server {
  listen 80;
  server_name api.xxx.com;
    
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD';

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host  $http_host;    
  } 
}

上面更改頭信息,還有一種,使用 rewrite 指令重定向URI來解決跨域問題。

upstream test {
  server 127.0.0.1:8080;
  server localhost:8081;
}
server {
  listen 80;
  server_name api.xxx.com;
  location / { 
    root  html;                   #去請求../html文件夾裏的文件
    index  index.html index.htm;  #首頁響應地址
  }
  # 用於攔截請求,匹配任何以 /api/開頭的地址,
  # 匹配符合之後,中止往下搜索正則。
  location ^~/api/{ 
    # 表明重寫攔截進來的請求,而且只能對域名後邊的除去傳遞的參數外的字符串起做用,
    # 例如www.a.com/proxy/api/msg?meth=1&par=2重寫,只對/proxy/api/msg重寫。
    # rewrite後面的參數是一個簡單的正則 ^/api/(.*)$,
    # $1表明正則中的第一個(),$2表明第二個()的值,以此類推。
    rewrite ^/api/(.*)$ /$1 break;
    
    # 把請求代理到其餘主機 
    # 其中 http://www.b.com/ 寫法和 http://www.b.com寫法的區別以下
    # 若是你的請求地址是他 http://server/html/test.jsp
    # 配置一: http://www.b.com/ 後面有「/」 
    #         將反向代理成 http://www.b.com/html/test.jsp 訪問
    # 配置一: http://www.b.com 後面沒有有「/」 
    #         將反向代理成 http://www.b.com/test.jsp 訪問
    proxy_pass http://test;

    # 若是 proxy_pass  URL 是 http://a.xx.com/platform/ 這種狀況
    # proxy_cookie_path應該設置成 /platform/ / (注意兩個斜槓之間有空格)。
    proxy_cookie_path /platfrom/ /;

    # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_header
    # 設置 Cookie 頭經過
    proxy_pass_header Set-Cookie;
  } 
}

跳轉到帶www的域上面

server {
    listen 80;
    # 配置正常的帶www的域名
    server_name www.wangchujiang.com;
    root /home/www/wabg/download;
    location / {
        try_files $uri $uri/ /index.html =404;
    }
}
server {
    # 這個要放到下面,
    # 將不帶www的 wangchujiang.com 永久性重定向到  https://www.wangchujiang.com
    server_name wangchujiang.com;
    rewrite ^(.*) https://www.wangchujiang.com$1 permanent;
}

代理轉發

upstream server-api{
    # api 代理服務地址
    server 127.0.0.1:3110;    
}
upstream server-resource{
    # 靜態資源 代理服務地址
    server 127.0.0.1:3120;
}
server {
    listen       3111;
    server_name  localhost;      # 這裏指定域名
    root /home/www/server-statics;
    # 匹配 api 路由的反向代理到API服務
    location ^~/api/ {
        rewrite ^/(.*)$ /$1 break;
        proxy_pass http://server-api;
    }
    # 假設這裏驗證碼也在API服務中
    location ^~/captcha {
        rewrite ^/(.*)$ /$1 break;
        proxy_pass http://server-api;
    }
    # 假設你的圖片資源所有在另一個服務上面
    location ^~/img/ {
        rewrite ^/(.*)$ /$1 break;
        proxy_pass http://server-resource;
    }
    # 路由在前端,後端沒有真實路由,在路由不存在的 404狀態的頁面返回 /index.html
    # 這個方式使用場景,你在寫React或者Vue項目的時候,沒有真實路由
    location / {
        try_files $uri $uri/ /index.html =404;
        #                               ^ 空格很重要
    }
}

監控狀態信息

經過 nginx -V 來查看是否有 with-http_stub_status_module 該模塊。

nginx -V 這裏 V 是大寫的,若是是小寫的 vnginx -v,則不會出現有哪些模塊,只會出現 nginx 的版本

location /nginx_status {
    stub_status on;
    access_log off;
}

經過 http://127.0.0.1/nginx_status 訪問出現下面結果。

Active connections: 3
server accepts handled requests
 7 7 5 
Reading: 0 Writing: 1 Waiting: 2 
  1. 主動鏈接(第 1 行)

當前與http創建的鏈接數,包括等待的客戶端鏈接:3

  1. 服務器接受處理的請求(第 2~3 行)

接受的客戶端鏈接總數目:7
處理的客戶端鏈接總數目:7
客戶端總的請求數目:5

  1. 讀取其它信(第 4 行)

當前,nginx讀請求鏈接
當前,nginx寫響應返回給客戶端
目前有多少空閒客戶端請求鏈接

代理轉發鏈接替換

location ^~/api/upload {
    rewrite ^/(.*)$ /wfs/v1/upload break;
    proxy_pass http://wfs-api;
}

ssl配置

超文本傳輸安全協議(縮寫:HTTPS,英語:Hypertext Transfer Protocol Secure)是超文本傳輸協議和SSL/TLS的組合,用以提供加密通信及對網絡服務器身份的鑑定。HTTPS鏈接常常被用於萬維網上的交易支付和企業信息系統中敏感信息的傳輸。HTTPS不該與在RFC 2660中定義的安全超文本傳輸協議(S-HTTP)相混。HTTPS 目前已是全部注重隱私和安全的網站的首選,隨着技術的不斷髮展,HTTPS 網站已再也不是大型網站的專利,全部普通的我的站長和博客都可以本身動手搭建一個安全的加密的網站。

建立SSL證書,若是你購買的證書,就能夠直接下載

sudo mkdir /etc/nginx/ssl
# 建立了有效期100年,加密強度爲RSA2048的SSL密鑰key和X509證書文件。
sudo openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
# 上面命令,會有下面須要填寫內容
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc.
Organizational Unit Name (eg, section) []:Ministry of Water Slides
Common Name (e.g. server FQDN or YOUR name) []:your_domain.com
Email Address []:admin@your_domain.com

建立自簽證書

首先,建立證書和私鑰的目錄
# mkdir -p /etc/nginx/cert
# cd /etc/nginx/cert
建立服務器私鑰,命令會讓你輸入一個口令:
# openssl genrsa -des3 -out nginx.key 2048
建立簽名請求的證書(CSR):
# openssl req -new -key nginx.key -out nginx.csr
在加載SSL支持的Nginx並使用上述私鑰時除去必須的口令:
# cp nginx.key nginx.key.org
# openssl rsa -in nginx.key.org -out nginx.key
最後標記證書使用上述私鑰和CSR:
# openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt

查看目前nginx編譯選項

sbin/nginx -V

輸出下面內容

nginx version: nginx/1.7.8
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx-1.7.8 --with-http_ssl_module --with-http_spdy_module --with-http_stub_status_module --with-pcre

若是依賴的模塊不存在,能夠進入安裝目錄,輸入下面命令從新編譯安裝。

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

運行完成以後還須要make (不用make install)

# 備份nginx的二進制文件
cp -rf /usr/local/nginx/sbin/nginx  /usr/local/nginx/sbin/nginx.bak
# 覆蓋nginx的二進制文件
cp -rf objs/nginx   /usr/local/nginx/sbin/

HTTPS server

server {
    listen       443 ssl;
    server_name  localhost;

    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    # 禁止在header中出現服務器版本,防止黑客利用版本漏洞攻擊
    server_tokens off;
    # 設置ssl/tls會話緩存的類型和大小。若是設置了這個參數通常是shared,buildin可能會參數內存碎片,默認是none,和off差很少,停用緩存。如shared:SSL:10m表示我全部的nginx工做進程共享ssl會話緩存,官網介紹說1M能夠存放約4000個sessions。 
    ssl_session_cache    shared:SSL:1m; 

    # 客戶端能夠重用會話緩存中ssl參數的過時時間,內網系統默認5分鐘過短了,能夠設成30m即30分鐘甚至4h。
    ssl_session_timeout  5m; 

    # 選擇加密套件,不一樣的瀏覽器所支持的套件(和順序)可能會不一樣。
    # 這裏指定的是OpenSSL庫可以識別的寫法,你能夠經過 openssl -v cipher 'RC4:HIGH:!aNULL:!MD5'(後面是你所指定的套件加密算法) 來看所支持算法。
    ssl_ciphers  HIGH:!aNULL:!MD5;

    # 設置協商加密算法時,優先使用咱們服務端的加密套件,而不是客戶端瀏覽器的加密套件。
    ssl_prefer_server_ciphers  on;

    location / {
        root   html;
        index  index.html index.htm;
    }
}

強制將http重定向到https

server {
    listen       80;
    server_name  example.com;
    rewrite ^ https://$http_host$request_uri? permanent;    # 強制將http重定向到https
    # 在錯誤頁面和「服務器」響應頭字段中啓用或禁用發射nginx版本。 防止黑客利用版本漏洞攻擊
    server_tokens off;
}

兩個虛擬主機

純靜態-html 支持

http {
    server {
        listen          80;
        server_name     www.domain1.com;
        access_log      logs/domain1.access.log main;
        location / {
            index index.html;
            root  /var/www/domain1.com/htdocs;
        }
    }
    server {
        listen          80;
        server_name     www.domain2.com;
        access_log      logs/domain2.access.log main;
        location / {
            index index.html;
            root  /var/www/domain2.com/htdocs;
        }
    }
}

虛擬主機標準配置

http {
  server {
    listen          80 default;
    server_name     _ *;
    access_log      logs/default.access.log main;
    location / {
       index index.html;
       root  /var/www/default/htdocs;
    }
  }
}

爬蟲過濾

根據 User-Agent 過濾請求,經過一個簡單的正則表達式,就能夠過濾不符合要求的爬蟲請求(初級爬蟲)。

~* 表示不區分大小寫的正則匹配

location / {
    if ($http_user_agent ~* "python|curl|java|wget|httpclient|okhttp") {
        return 503;
    }
    # 正常處理
    # ...
}

防盜鏈

location ~* \.(gif|jpg|png|swf|flv)$ {
   root html
   valid_referers none blocked *.nginxcn.com;
   if ($invalid_referer) {
     rewrite ^/ www.nginx.cn
     #return 404;
   }
}

虛擬目錄配置

alias指定的目錄是準確的,root是指定目錄的上級目錄,而且該上級目錄要含有location指定名稱的同名目錄。

location /img/ {
    alias /var/www/image/;
}
# 訪問/img/目錄裏面的文件時,ningx會自動去/var/www/image/目錄找文件
location /img/ {
    root /var/www/image;
}
# 訪問/img/目錄下的文件時,nginx會去/var/www/image/img/目錄下找文件。]

防盜圖配置

location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf) {
    valid_referers none blocked *.jslite.io;
    if ($invalid_referer) {
        rewrite ^/  http://wangchujiang.com/piratesp.png;
    }
}

屏蔽.git等文件

location ~ (.git|.gitattributes|.gitignore|.svn) {
    deny all;
}

域名路徑加不加須要都能正常訪問

http://wangchujiang.com/api/index.php?a=1&name=wcj
                                  ^ 有後綴

http://wangchujiang.com/api/index?a=1&name=wcj
                                 ^ 沒有後綴

nginx rewrite規則以下:

rewrite ^/(.*)/$ /index.php?/$1 permanent;
if (!-d $request_filename){
        set $rule_1 1$rule_1;
}
if (!-f $request_filename){
        set $rule_1 2$rule_1;
}
if ($rule_1 = "21"){
        rewrite ^/ /index.php last;
}

錯誤問題

The plain HTTP request was sent to HTTPS port

解決辦法,fastcgi_param HTTPS $https if_not_empty 添加這條規則,

server {
    listen 443 ssl; # 注意這條規則
    server_name  my.domain.com;
    
    fastcgi_param HTTPS $https if_not_empty;
    fastcgi_param HTTPS on;

    ssl_certificate /etc/ssl/certs/your.pem;
    ssl_certificate_key /etc/ssl/private/your.key;

    location / {
        # Your config here...
    }
}

Nginx 模塊

  • Nginx Office Hours 一個 nginx 模塊,容許您僅在辦公時間內提供訪問訪問網站。

精品文章參考

相關文章
相關標籤/搜索