Nginx 虛擬主機 VirtualHost 配置



增加 Nginx 虛擬主機

配置 Virtual host 步驟如下:

1. 進入 nginx的安裝目錄,我的目錄是在/usr/local/nginx,找到nginx 的配置文件/usr/local/nginx/conf/nginx.conf並打開,在http{}范圍引入虛擬主機配置文件如下:

include vhost/*.conf;

2. 在/usr/local/nginx/conf/vhost目錄下,創建對應虛擬主機的配置文件 www.demo.com.conf (文件格式{域名}.conf),每個虛擬主機(域名)對應一個配置文件。打開配置文件, 添加服務如下:

server {
	listen       80;
	server_name www.demo.com;
     location / {
       root /var/www/demo;
       index index.html index.htm index.php;
     }
     //日志保存方式以及存放位置
	log_format www.demo.com '$remote_addr - $remote_user [$time_local] $request'
	'$status $body_bytes_sent $http_referer '
	'$http_user_agent $http_x_forwarded_for';
	access_log  /var/log/www.demo.com.log www.demo.com;
     //支持php,這里使用的是 FastCGI, 修改如下

     location ~ .*\.(php|php5)?$ {
        #網站目錄
        root /var/www/test;
        #phpcgi端口,默認9000
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        #document_root指向的就是網站目錄
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}

}

 

 

4. 重啟 Nginx 服務, 執行以下語句.

/etc/init.d/nginx reload
 

圖片防盜鏈

圖片作為重要的耗流量大的靜態資源, 可能網站主並不希望其他網站直接引用, Nginx 可以通過 referer 來防止外站盜鏈圖片.

server {
	listen       80;
	server_name demo.neoease.com;
	index index.html index.htm index.php;
	root  /var/www/demo_neoease_com;
 
	# 這里為圖片添加為期 1 年的過期時間, 並且禁止 Google, 百度和本站之外的網站引用圖片
	location ~ .*\.(ico|jpg|jpeg|png|gif)$ {
		expires 1y;
		valid_referers none blocked demo.neoease.com *.google.com *.baidu.com;
		if ($invalid_referer) {
			return 404;
		}
	}
 
	log_format demo.neoease.com '$remote_addr - $remote_user [$time_local] $request'
	'$status $body_bytes_sent $http_referer '
	'$http_user_agent $http_x_forwarded_for';
	access_log  /var/log/demo.neoease.com.log demo.neoease.com;
}

WordPress 偽靜態配置

如果將 WordPress 的鏈接結構設定為 /%postname%//%postname%.html 等格式時, 需要 rewrite URL, WordPress 提供 Apache 的 .htaccess 修改建議, 但沒告知 Nginx 該如何修改. 我們可以將 WordPress 的虛擬主機配置修改如下:

server {
	listen       80;
	server_name demo.neoease.com;
	index index.html index.htm index.php;
	root  /var/www/demo_neoease_com;
 
	location / {
		if (-f $request_filename/index.html){
			rewrite (.*) $1/index.html break;
		}
		if (-f $request_filename/index.php){
			rewrite (.*) $1/index.php;
		}
		if (!-f $request_filename){
			rewrite (.*) /index.php;
		}
	}
	rewrite /wp-admin$ $scheme://$host$uri/ permanent;
 
	location ~ .*\.(php|php5)?$ {
		fastcgi_pass unix:/tmp/php-cgi.sock;
		fastcgi_index index.php;
		include fcgi.conf;
	}
 
	log_format demo.neoease.com '$remote_addr - $remote_user [$time_local] $request'
	'$status $body_bytes_sent $http_referer '
	'$http_user_agent $http_x_forwarded_for';
	access_log  /var/log/demo.neoease.com.log demo.neoease.com;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM