CentOS 6(64-bit) + Nginx搭建静态文件服务器
Nginx搭建静态文件服务器
使用命令打开Nginx配置文件:
sudo vim /etc/nginx/conf.d/default.conf
将配置改为:
server { ...... ...... # 下面的东西是需要自行添加的配置 location ~ \.(png|gif|jpg|jpeg)$ { root /usr/share/nginx/images; #这个将替换`server->root`配置 # expires 1d; index default.jpg; } # 上面就是需要添加的东西了 # 对于满足以 .png/.gif/.jpg 结尾的url请求, # 将其根目录定义为 /usr/share/nginx/images # 文件的有效期为一天(如果需要可以取消注释) ...... ......}
设置完之后通过命令:
sudo service nginx restart重启Nginx后生效。
如果遇到启动失败,使用命令:
nginx -t
查看错误信息
Nginx搭建PHP运行环境
PHP运行环境安装一个 php-fpm包即可:
sudo yum install php-fpm
执行命令打开对应的配置文件:
sudo vim /etc/nginx/conf.d/default.conf
将server_name改为:
server_name localhost;
将第一个默认的 localtion改为:
location / { try_files $uri $uri=404;}
将 404 改为:
error_page 404 /404.html;
执行命令:
vim /etc/php-fpm.d/www.conf
查找并记住 listen内容(以下127.0.0.1:9000是我本机的设置):
listen = 127.0.0.1:9000
去掉Nginx配置文件里的PHP的配置改为如下:
# 同样是在server的区块里location ~ \.php$ { try_files $uri = 404; fastcgi_pass 127.0.0.1:9000; # 就是上面查找到的127.0.0.1:9000这个内容 fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params;}
可以得知我们的配置是正确的。
使用PHP上传文件
配置"php.ini"文件
sudo vim /etc/php.ini
如果不知道php.ini文件在哪里,请执行命令:
php -i | grep "Loaded Configuration File"
设置:
file_uploads = On
重启PHP服务:
sudo service php-fpm restart
在 /usr/share/nginx中创建HTML表单 upload.php:
<!DOCTYPE html><html><body><form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"></form></body></html>
注意:
- 确保表单的 method为 post
- enctype为 multipart/form-data确保可以接收文件
创建上传的PHP脚本
<?php $target_dir = "images/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } }?>
解释:
- $target_dir = "images/"表示文件存放的目录
- $target_file表示文件上传的路径
- $uploadOk=1暂未使用
- $imageFileType包含了文件的扩展名
- 接着就是判断文件是否是图片
检查文件是否已存在
// Check if file already existsif (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0;}
限制文件大小
// Check file sizeif ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0;}
限制文件类型
// Allow certain file formatsif($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0;}
完整的代码
500000) { echo "Sorry, your file is too large."; $uploadOk = 0;}// Allow certain file formatsif($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0;}// Check if $uploadOk is set to 0 by an errorif ($uploadOk == 0) { echo "Sorry, your file was not uploaded.";// if everything is ok, try to upload file} else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; }}?>
遇到php报 500 Server internal error错误怎么办?
在对应的php文件中增加:
ini_set('display_errors', 1);
在.htaccess文件中(如果没有该文件则手动创建一个空文件)添加:
php_flag display_errors 1
遇到php报 move_uploaded_file:failed to open stream: Permission denied in /usr/share/nginx/images怎么办?
在对应的php文件中增加:
echo exec('whoami');
比如输出的是:
www-data
执行以下语句赋予权限(语句中的www-data应该对应whoami的输出值):
sudo chown www-data /usr/share/nginx/imagessudo chmod 0755 /usr/share/nginx/images
[参考文章] https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-centos-7

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov
