Centos7下Nginx代理和二級域名配置

Centos7下Nginx代理和二級域名配置


nginx的安裝步驟請閱讀上一篇文章。

一、nginx的反向代理配置

編輯nginx的配置文件(找到自己的配置文件)

vim /usr/local/nginx/conf/nginx.conf
user root;        #這裏是nginx運行的用戶
worker_processes 2;      #設置nginx服務的worker子進程:
error_log logs/error.log;#記錄nginx錯誤日誌:
pid logs/nginx.pid;      #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; 	 #日誌存放位置

    #這是server段的配置 可配置多個server,即二級域名配置
    #server1 : 如,靜態資源的配置
    server {
        listen       80;
        server_name  www.test.com;    #要訪問的域名,我這裏用的測試域名,如果有多個,用逗號分開
        charset utf8;

        #nginx的默認訪問地址 即直接訪問上訴的server_name配置的域名展示的Welcome to nginx!頁面
        location / {
            root   html;
            index  index.html index.htm;
        }
	
        # 圖片文件存放路徑
        location /images/ {
            alias  /home/file/images/;# 這裏需要使用alias而不是root,切路徑末尾需要有/,否則訪問靜態資源時會出現404
            autoindex on;
        }
    }
}

二、基於nginx的二級域名配置

http{....}配置中新增server{.....}配置

    #server2:如,配置項目的域名,如此啊配置可理解爲二級域名的配置
    server {
        listen       80;
        server_name  project.test.com;    #要訪問的域名,如果有多個,用逗號分開
        charset utf8;

	#nginx的默認訪問地址 即直接訪問上訴的server_name配置的域名展示的Welcome to nginx!頁面
	location / {
		root   html;
		index  index.html index.htm;
	}
	
        location /test {              
		proxy_pass http://127.0.0.1:8888/;	#這裏http://127.0.0.1:8888/是訪問該服務器上的某個項目的訪問路徑,也可寫成ip:端口
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header X-Forwarded-Proto $scheme;
		proxy_set_header X-Forwarded-Port $server_port;
         }
    }

三、注意

靜態資源路徑中配置root時,是無法訪問資源的;如下配置,訪問資源時會報404

server {
        listen       80;
        server_name  www.test.com; 
        charset utf8;
	
        # 圖片文件存放路徑
        location /images/ {
            root /home/file/images/;# 這裏需要使用alias而不是root,切路徑末尾需要有/,否則訪問靜態資源時會出現404
            autoindex on;
        }
    }

而nginx提供了另外一個靜態路徑配置  : alias

alias與root區別

官方root解釋:
#Sets the root directory for requests. For example, with the following configuration
location /i/ {
    root /data/w3;
}
#The /data/w3/i/test.jpg file will be sent in response to the "/i/test.jpg" request
官方alias解釋:

#Defines a replacement for the specified location. For example, with the following configuration
location /i/ {
    alias /data/w3/;
}
#on request of “/i/test.jpg”, the file "/data/w3/test.jpg" will be sent.
假設我們的靜態資源存放地址爲:/data/w3/test.jpg

當訪問http://ip:端口/i/test.jpg時

    root是去/data/w3/i/test.jpg請求文件

    alias是去/data/w3/test.jpg請求請求文件

因此:

root響應的路徑:配置的路徑 + 完整訪問路徑(完整的location配置路徑 + 靜態文件)
alias響應的路徑:配置路徑 + 靜態文件(去除location中配置的路徑)






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章