如何在Ubuntu 16.04搭建支持PHP 7的Nginx环境

安装软件包

更新Ubuntu并获取nginx和PHP包。

# sudo apt-get update && sudo apt-get -y upgrade
# sudo apt-get -y install nginx php7.0 php7.0-fpm

可以检查nginx和php-fpm服务是否在systemd中运行。

# sudo systemctl status nginx
# sudo systemctl status php7.0-fpm

如果SystemD确认这两个服务都在运行,则服务器实际上应该为UP,
在浏览器中打开http://localhost可以查看默认的Nginx欢迎页面。

配置

现在nginx已经可以使用。
为了提高安全性需要修改nginx一些配置。
nginx配置文件的根目录位于 /etc/nginx
在Ubuntu中有默认值,使配置流程更加容易。

nginx.conf.

nginx的主要配置文件是nginx.conf

如果我们想提高性能,则注释后的GZIP选项将有助于压缩,并可以加速速度。
在安全方面,添加以下三行将有助于防止恶意活动。

add_header X-Frame-Options SAMEORoirN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

站点配置

nginx root中有两个文件夹,sites-availablesites-enabled
sites-available存储网站配置。
sites-enabled包含“可用的”网站“中的配置文件的符号链接。
这样,启用和禁用站点就像创建和删除符号链接一样简单。

/etc/nginx/sites-available/yoursite中创建一个文件。
此文件将包含新PHP 7网站的任何特定于站点的配置。

这是一个相当基础的配置。

server { 

	#Nginx should listen on port 80 for requests to yoursite.com
	listen 80; 
	server_name yoursite.com; 
	#Create access and error logs in /var/log/nginx
	access_log /var/log/nginx/yoursite.access_log main; 
	error_log /var/log/nginx/yoursite.error_log info; 
	#Nginx should look in /var/www/yoursite for your website
	root /var/www/yoursite/;
	#The homepage of your website is a file called index.php 
	index index.php; 
	#Specifies that Nginx is looking for .php files
	location ~ \.php$ { 
		#If a file isn’t found, 404
		try_files $uri =404; 
		#Include Nginx’s fastcgi configuration
		include /etc/nginx/fastcgi.conf;
		#Look for the FastCGI Process Manager at this location 
		fastcgi_pass unix:/run/php/php7.0-fpm.sock; 
	} 
}

保存它并移动到'sites enabled'目录。从那里,创建符号链接回到刚才创建的文件。

# cd /etc/nginx/sites-enabled
# sudo ln -s /etc/nginx/sites-available/yoursite

php.ini安全

可以对php.ini配置文件进行一些简单的调整有助于保护PHP。

打开文件 /etc/php/7.0/fpm/php.ini

首先查找“disable_functions”并添加phpinfo,system,mail,exec到末尾。
然后查找“file_uploads”并将其设置为 Off
接下来,查找sql.safe_mode并设置为 Off
最后,找到“allow_url_fopen”,并将其设置为 Off
在文件最后面添加一行。

register_globals = Off

重新启动服务, 使设置生效:

# sudo systemctl restart php7.0-fpm
# sudo systemctl restart nginx

将php文件和html文件放到 /var/www/yoursite中即可被访问。

日期:2020-07-07 20:56:02 来源:oir作者:oir