這篇文章主要介紹了Nginx服務器的安裝與一些基本配置總結,包括靜態化與負載均衡等重要設置的方法記錄,需要的朋友可以參考下
安裝
ubuntu下
- sudo apt-get install nginx
啟動
- sudo /etc/init.d/nginx start #通過init.d下的啟動文件啟動。
- sudo service nginx start#通過ubuntu的服務管理器啟動
配置文件位置
- /etc/nginx/nginx.conf
編譯安裝
1.先決條件
(1).gcc
- apt-get install gcc
(2).pcre(Perl Compatible Regular Expression)
- apt-get install libpcre3 libpcre3-dev
(3).zlib
- apt-get install zliblg zliblg-dev
(4).openssl
- apt-get install openssl opensll-dev
- #如果非apt,可以使用下載包手動編譯安裝的方式處理
2.下載包
www.nginx.net 下載穩定版
- wget http://nginx.org/download/nginx-1.4.4.tar.gz
3.解壓安裝
- tar -xzvf nginx-1.4.4.tar.gz
- #默認,安裝目錄/usr/local/nginx
- ./configure
- make
- make install
- #配置
- ./configure --conf-path=/etc/nginx/nginx.conf
可以配置一些其他選項
安裝后查看下目錄下的Configuration summary
4.init腳本
需要給nginx建立一個init腳本
從網上撈一個,放入/etc/init.d/nginx
推薦編譯配置
1.使用不同prefix,方便指定不同版本,也便于升級
- ./configure --prefix=/usr/local/nginx-1.4.4
基本操作
查看幫助
- /usr/local/nginx/sbin/nginx -h
立即停止進程(TERM信號)
- /usr/local/nginx/sbin/nginx -s stop
溫和停止進程(QUIT信號)
- /usr/local/nginx/sbin/nginx -s quit
重加載
- /etc/init.d/nginx reload #有init腳本情況下
- /usr/local/nginx/sbin/nginx -s reload #原生
檢測配置文件是否正確
- /usr/local/nginx/sbin/nginx -t #生產路徑下的
- /usr/local/nginx/sbin/nginx -t -c /home/ken/tmp/test.conf #可以測試某個臨時文件
HTTP基本配置 配置說明
注釋,#
每條指令總是以分好結束(;)
配置繼承:在一個區塊中嵌套其他區段,那么被嵌套的區段會繼承其父區段的設置
字符串,可以沒有引號,但是如果存在特殊字符(空格,分號,花括號)需要用引號引起
單位:大小(k/K m/M) 時間值(ms/s/m/h/d/w/M/y 默認s)
模塊提供各種變量值,可以進行讀取和賦值(每個模塊提供變量列表需要自己去查)
配置文件目錄結構
/usr/local/nginx/conf/
- mime.types 一個文件擴展列表,它們與MIME類型關聯
- fastcgi.conf 與FastCGI相關的配置文件
- proxy.conf 與Proxy相關的配置文件
- nginx.conf 應用程序的基本配置文件
- sites/
|- a.conf #允許給每個單獨網站建立一個配置文件
|- b.conf
|- dir/
|- c.conf
需要在nginx.conf中使用包含命令
- include sites/*.conf;
- include sites/*/*.conf;
配置文件結構
- http { #嵌入配置文件的根部, 一個http里可以配置多個server
- server { #聲明一個站點
- server_name www.website.com; #監聽的主機名
- listen 80; #監聽套接字所使用的ip地址和端口號
- error_page 404 /not_found.html;
- error_page 500 501 502 503 504 /server_error.html;
- index index.html;
- root /var/www/website/com/html; #定義文檔的根目錄
- #location, 通過制定的模式與客戶端請求的URI相匹配
- location / { #網站的特定位置
- }
- location /admin/ { #網站的特定位置 #
- alias /var/www/locked/; #只能放在 location區段中,為指定路徑提供別名
- }
- #操作符,匹配時跟定義順序無關
- location = /abcd { #精確匹配,不能用正則
- }
- location /abc/ { #url必須以指定模式開始,不能用正則
- }
- location ^~ /abcd$ { #吳標致行為,URI定位必須以指定模式開始,如果匹配,停止搜索其他模式
- }
- location ~ ^/abcd$ { #正則匹配,區分大小寫
- }
- location ~* ^/abcd$ { #正則匹配,不區分大小寫
- }
- location @test { #定義location區段名,客戶端不能訪問,內部產生的請求可以,例如try_files或error_page
- }
- }
- }
模塊 模塊化
nginx真正的魅力在于它的模塊,整個應用程序建立在一個模塊化系統之上,在編譯時,可以對每一個模塊進行啟用或者禁用
index模塊
定義往回走哪index頁
- index index.php index.html /data/website/index.html;
#可以指定多個,但是ngxin提供第一個找到的文件
Log模塊
access_log /file/path;
error_log /file/path error; #level: debug/info/notice/warn/error/crit
日志格式
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 /var/log/test.log main;
Real IP模塊
默認編譯nginx不包含這個模塊
當通過nginx將用戶請求進行轉發時,接收請求的應用要拿到用戶的真實IP(經轉發拿到的是服務器的IP)
- real_ip_header X-Forwarded-For;
Access模塊
可以禁用ip段
語法
- #如果規則之間有沖突,會以最前面匹配的規則為準
- deny IP;
- deny subnet;
- allow IP;
- allow subnet;
- # block all ips
- deny all;
- # allow all ips
- allow all;
配置一個blockips.conf,然后在nginx.conf中include
e.g
- location {
- allow 127.0.0.1; #允許本地ip 注意順序,allow要放在前面
- deny all; #禁止其他ip
- }
Rewrite模塊
作用:執行URL重定向,允許你去掉帶有惡意的URL,包含多個參數(修改)
利用正則的匹配,分組和引用,達到目的
break/return/set等
- if (-f $uri) {
- break
- }
- if ($uri ~ ^/admin/){
- return 403;
- }
- if ($uri ~ ^/search/(.*)$) {
- set $query $1;
- rewrite ^ /search.php?q=$query?;
- }
例子
- A:http://website.com/search/some-search-keywords
- B:http://website.com/search.php?q=some-search-keywords
- rewrite ^/search/(.*)$ /search.php?q=$1?;
- A:http://website.com/user/31/James
- B:http://website.com/user.php?id=31&name=James
- rewrite ^/user/([0-9]+)/(.+)$ /user.php?id=$1&name=$2?;
- A:http://website.com/index.php/param1/param2/param3
- B:http://website.com/index.php/?p1=param1&p2=param2&p3=param3
- rewrite ^/index.php/(.*)/(.*)/(.*)$ /index.php?p1=$1&p2=$2&p3=$3?;
rewrite語法
- rewrite A B option;
options:
last :表示完成rewrite
break:本規則匹配完成后,終止匹配,不再匹配后面的規則
redirect:返回302臨時重定向,地址欄會顯示跳轉后的地址
permanent:返回301永久重定向,地址欄會顯示跳轉后的地址
Proxy模塊
默認模塊,允許你講客戶端的HTTP請求轉到后端服務器
- location / {
- proxy_pass_header Server; #該指令強制一些被忽略的頭傳遞到客戶端
- proxy_redirect off; #允許改寫出現在HTTP頭卻被后端服務器觸發重定向的URL,對相應本身不做任何處理
- proxy_set_header Host $http_host; #允許你重新定義代理header值再轉到后端服務器.目標服務器可以看到客戶端的原始主機名
- proxy_set_header X-Real-IP $remote_addr; #目標服務器可以看到客戶端的真實ip,而不是轉發服務器的ip
- proxy_set_header X-Scheme $scheme;
- proxy_pass http://localhost:8080;
- }
upstream模塊
- upstream up_name {
- server 192.168.0.1:9000 weight=5; #權重
- server 192.168.0.2:9000 weight=5 max_fails=5 fail_timeout=60s; #在60s內,其錯誤通信超過5次,認為該服務失效
- server 192.168.0.3:9000 down; #服務標記為離線,不再使用
- server 192.168.0.4:9000 backup; #備份服務器,其他全部宕機了才啟用
- }
其他 配置靜態化目錄
- location /static/
- {
- root /var/www/app/;
- autoindex off;
- }
負載均衡
- http {
- include mime.types;
- default_type application/octet-stream;
- keepalive_timeout 120;
- tcp_nodelay on;
- upstream up_localhost {
- server 127.0.0.1:8000 weight=5;
- server 127.0.0.1:8001 weight=10;
- }
- server {
- listen 80;
- server_name localhost;
- location /{
- proxy_pass http://up_localhost;
- proxy_set_header Host $host;
- proxy_set_header X-Real_IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- }
- }
- }
控制頁面緩存
- location ~ /.(htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt)$ {
- root /opt/webapp;
- expires 24h;
- }
- expires 1 January, 1970, 00:00:01 GMT;
- expires 60s;
- expires 30m;
- expires 24h;
- expires 1d;
- expires max;
- expires off;
nginx的內置變量
$arg_PARAMETER 這個變量包含在查詢字符串時GET請求PARAMETER的值。
$args 這個變量等于請求行中的參數。
$binary_remote_addr 二進制碼形式的客戶端地址。
$body_bytes_sent
$content_length 請求頭中的Content-length字段。
$content_type 請求頭中的Content-Type字段。
$cookie_COOKIE cookie COOKIE的值。
$document_root 當前請求在root指令中指定的值。
$document_uri 與$uri相同。
$host 請求中的主機頭字段,如果請求中的主機頭不可用,則為服務器處理請求的服務器名稱。
$is_args 如果$args設置,值為"?",否則為""。
$limit_rate 這個變量可以限制連接速率。
$nginx_version 當前運行的nginx版本號。
$query_string 與$args相同。
$remote_addr 客戶端的IP地址。
$remote_port 客戶端的端口。
$remote_user 已經經過Auth Basic Module驗證的用戶名。
$request_filename 當前連接請求的文件路徑,由root或alias指令與URI請求生成。
$request_body 這個變量(0.7.58+)包含請求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比較有意義。
$request_body_file 客戶端請求主體信息的臨時文件名。
$request_completion 請求完成
$request_method 這個變量是客戶端請求的動作,通常為GET或POST。包括0.8.20及之前的版本中,這個變量總為main request中的動作,如果當前請求是一個子請求,并不使用這個當前請求的動作。
$request_uri 這個變量等于包含一些客戶端請求參數的原始URI,它無法修改,請查看$uri更改或重寫URI。
$schemeHTTP 方法(如http,https)。按需使用,例:
rewrite ^(.+)$ $scheme://example.com$1 redirect;
$server_addr 服務器地址,在完成一次系統調用后可以確定這個值,如果要繞開系統調用,則必須在listen中指定地址并且使用bind參數。
$server_name 服務器名稱。
$server_port 請求到達服務器的端口號。
$server_protocol 請求使用的協議,通常是HTTP/1.0或HTTP/1.1。
$uri 請求中的當前URI(不帶請求參數,參數位于$args),可以不同于瀏覽器傳遞的$request_uri的值,它可以通過內部重定向,或者使用index指令進行修改。
使用獨立目錄, 然后include具體配置
目錄
- nginx.conf
- site/
- a.conf
- b.conf
- nginx.conf
- http {
- .......
- include /etc/nginx/conf.d/*.conf;
- include sites/*.conf;
- }
gzip on
加到http模塊中, 開啟gzip, 注意gzip_types配置得是壓縮的資源類型
nginx.conf
- http {
- .....
- gzip on;
- gzip_min_length 1k;
- gzip_comp_level 5;
- gzip_proxied expired no-cache no-store private auth;
- gzip_types text/plain text/css application/javascript text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json image/x-icon image/png image/jpg image/jpeg application/font-woff;
- gzip_vary on;
- }
- for multi processers
- nginx.conf
- worker_processes 4;
- events {
- worker_connections 2048;
- use epoll;
- multi_accept on;
- }
- worker_rlimit_nofile 100000;
- static file cache
- location ~* /.(?:css|js)$ {
- expires 12h;
- access_log off;
- add_header Cache-Control "public";
- proxy_pass http://127.0.0.1:5000;
- proxy_redirect off;
- }
- proxy pass
- location /
- {
- proxy_pass http://127.0.0.1:8000;
- proxy_pass_header Server;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Scheme $scheme;
- proxy_set_header Host $http_host;
- proxy_redirect off;
- }
可以設置超時時間
- proxy_connect_timeout 500s;
- proxy_read_timeout 500s;
- proxy_send_timeout 500s;
- 靜態目錄 or 文件
- location /movies/ {
- alias /Volumes/Media/Movies/;
- allow all;
- }
- location = /abc.txt {
- alias /data/www/static/abc.txt;
- expires 30d;
- access_log off;
- }
靜態站
- server {
- listen 192.168.1.1:80;
- server_name www.abc.com;
- client_max_body_size 1M;
- access_log logs/blog_access.log;
- error_log logs/blog_error.log;
- root /data/static_site_dir;
- index index.html;
- }
return
直接return
語法
- return http_code;
- return http_code "content";
e.g.
- location /api/test/ {
- return 403;
- }
- location /stat/ {
- return 204;
- }
- location /ping/ {
- return 200;
- }
for mobile
移動端和網站端互相跳轉
- location = / {
- try_files $uri @mobile_rewrite;
- }
- location ~ ^/(login|register|search|album|404|album//d+|item//d+|topic)$ {
- try_files $uri @mobile_rewrite;
- }
- location @mobile_rewrite {
- if ($http_user_agent ~* "(android|bb/d+|meego).+mobile|avantgo|bada//|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)//|plucker|pocket|psp|series(4|6)0|symbian|treo|up/.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
- set $mobile_rewrite perform;
- }
- if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s/-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|/-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw/-(n|u)|c55//|capi|ccwa|cdm/-|cell|chtm|cldc|cmd/-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc/-s|devi|dica|dmob|do(c|p)o|ds(12|/-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(/-|_)|g1 u|g560|gene|gf/-5|g/-mo|go(/.w|od)|gr(ad|un)|haie|hcit|hd/-(m|p|t)|hei/-|hi(pt|ta)|hp( i|ip)|hs/-c|ht(c(/-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i/-(20|go|ma)|i230|iac( |/-|//)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |//)|klon|kpt |kwc/-|kyo(c|k)|le(no|xi)|lg( g|//(k|l|u)|50|54|/-[a-w])|libw|lynx|m1/-w|m3ga|m50//|ma(te|ui|xo)|mc(01|21|ca)|m/-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(/-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)/-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|/-([1-8]|c))|phil|pire|pl(ay|uc)|pn/-2|po(ck|rt|se)|prox|psio|pt/-g|qa/-a|qc(07|12|21|32|60|/-[2-7]|i/-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55//|sa(ge|ma|mm|ms|ny|va)|sc(01|h/-|oo|p/-)|sdk//|se(c(/-|0|1)|47|mc|nd|ri)|sgh/-|shar|sie(/-|m)|sk/-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h/-|v/-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl/-|tdg/-|tel(i|m)|tim/-|t/-mo|to(pl|sh)|ts(70|m/-|m3|m5)|tx/-9|up(/.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|/-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(/-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas/-|your|zeto|zte/-)") {
- set $mobile_rewrite perform;
- }
- if ($arg_mobile = 'no') {
- set $mobile_rewrite do_not_perform;
- }
- if ($arg_mobile = 'yes') {
- set $mobile_rewrite perform;
- }
- if ($mobile_rewrite = perform) {
- rewrite ^ http://$server_name/m$request_uri permanent;
- break;
- }
- proxy_pass http://127.0.0.1:5000;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header Host $http_host;
- proxy_redirect off;
- }
- location /m/
- {
- set $pc_rewrite 1;
- if ($http_user_agent ~* "(android|bb/d+|meego).+mobile|avantgo|bada//|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)//|plucker|pocket|psp|series(4|6)0|symbian|treo|up/.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
- set $pc_rewrite 0;
- }
- if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s/-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|/-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw/-(n|u)|c55//|capi|ccwa|cdm/-|cell|chtm|cldc|cmd/-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc/-s|devi|dica|dmob|do(c|p)o|ds(12|/-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(/-|_)|g1 u|g560|gene|gf/-5|g/-mo|go(/.w|od)|gr(ad|un)|haie|hcit|hd/-(m|p|t)|hei/-|hi(pt|ta)|hp( i|ip)|hs/-c|ht(c(/-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i/-(20|go|ma)|i230|iac( |/-|//)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |//)|klon|kpt |kwc/-|kyo(c|k)|le(no|xi)|lg( g|//(k|l|u)|50|54|/-[a-w])|libw|lynx|m1/-w|m3ga|m50//|ma(te|ui|xo)|mc(01|21|ca)|m/-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(/-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)/-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|/-([1-8]|c))|phil|pire|pl(ay|uc)|pn/-2|po(ck|rt|se)|prox|psio|pt/-g|qa/-a|qc(07|12|21|32|60|/-[2-7]|i/-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55//|sa(ge|ma|mm|ms|ny|va)|sc(01|h/-|oo|p/-)|sdk//|se(c(/-|0|1)|47|mc|nd|ri)|sgh/-|shar|sie(/-|m)|sk/-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h/-|v/-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl/-|tdg/-|tel(i|m)|tim/-|t/-mo|to(pl|sh)|ts(70|m/-|m3|m5)|tx/-9|up(/.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|/-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(/-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas/-|your|zeto|zte/-)") {
- set $pc_rewrite 0;
- }
- if ($pc_rewrite = 1) {
- rewrite ^/m/(.*)$ http://$server_name/$1 permanent;
- }
- proxy_pass http://127.0.0.1:5000;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header Host $http_host;
- proxy_redirect off;
- }
- redirect to www
- server {
- server_name abc.com;
- rewrite ^(.*) http://www.abc.com$1 permanent;
- }
- allow and deny
訪問ip控制
- location /test/ {
- allow 192.168.1.1;
- deny all;
- }
負載均衡
nginx.conf
- http {
- upstream A {
- server 192.168.1.1:5000;
- server 192.168.1.2:5000;
- }
- }
sites/a.conf
- server {
- location / {
- proxy_pass A;
- }
- }
其他
- centos service cmds
檢查配置文件正確性
- service nginx configtest
重新加載配置
- service nginx reload
新聞熱點
疑難解答