Nginx搭建靜態文件服務器
[官方教程]https://www.nginx.com/resources/admin-guide/serving-static-content/
打開Nginx的配置文件:/etc/nginx/sites-available/default
,找到server
,添加以下配置:
server {
# 監聽來自所有網絡上的80端口的請求
listen 0.0.0.0:8080;
# 這個server的根目錄
root /usr/share/nginx/files;
# 下面的東西是需要自行添加的配置
location ~ \.(png|gif|jpg)$ {
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運行環境安裝一個php5-fpm
包即可:
sudo apt-get install php5-fpm
去掉Nginx配置文件里關於php5-fpm的三行(A/B/C,當然也要包含X/Y兩行)注釋:
# 同樣是在server的區塊里
location ~ .*\.php$ { # X
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock; # A
fastcgi_index index.php; # B
include fastcgi_params; # C
} # Y
關於A行可以先執行命令:
vim /etc/php5/fpm/pool.d/www.conf
查找到:
listen = /var/run/php5-fpm.sock
可以得知我們的配置是正確的。
使用PHP上傳文件
配置"php.ini"文件
sudo vim /etc/php5/fpm/php.ini
設置:
file_uploads = On
在/usr/share/nginx
中創建HTML表單upload.php
:
<?php
// 這兩行是用來調試錯誤的,詳見后文中的備注
// ini_set('display_errors', 1);
// echo exec('whoami');
// 該方法會將所有收到的文件以GUID的文件名存儲起來
function GUID()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}
return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}
$d = date('Y-m-d'); // 日期格式 yyyy-MM-dd,用來將圖片文件按日期分組
$target_dir = "images/".$d.'/'; // 存儲目錄
$uploadOk = 1; // 判斷是否通過檢測的標記
$errorMsg = array(); // 如果遇到上傳錯誤,錯誤信息列表
$imageFileType = pathinfo(basename($_FILES["fileToUpload"]["name"]),PATHINFO_EXTENSION); // 文件的擴展名
$file_name_raw = GUID() . '.' . $imageFileType; // 存儲到服務器端的唯一文件名
$target_file_unique = ''; // 存儲之后的文件名相對路徑
$tokens_valid = array('ABC','78C0C020-6DCA-4B97-82CD-D83FEF80331A'); // token列表,用來控制權限, 可以定期手動更新
// 由於是獨立的站點,因此簡單的用寫死的token作為上傳圖片權限的基本驗證
if(!in_array($_POST['token'], $tokens_valid)){
array_push($errorMsg, "You are not authorized to upload images.");
$uploadOk = 0;
}
else{
$target_file_unique = $target_dir . $file_name_raw;
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check === false){
array_push($errorMsg, "File is not an image.");
$uploadOk = 0;
}
}
if(is_dir($target_dir)==false){
mkdir($target_dir, 0755);
}
// 文件大小不能超過50M
if ($_FILES["fileToUpload"]["size"] > 50000000) {
array_push($errorMsg, "Sorry, your file is too large. It must be smaller than 50M.");
$uploadOk = 0;
}
// 判斷是否是支持的格式
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
array_push($errorMsg, "Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
$uploadOk = 0;
}
// 是否上傳成功,有沒有遇到內部錯誤
if (!move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file_unique)) {
array_push($errorMsg, "Sorry, there was an error uploading your file.");
$uploadOk = 0;
}
}
// 如果有錯誤,則將錯誤信息全部返回到客戶端
$errorMsgOutput = '';
foreach($errorMsg as $msg){
$errorMsgOutput = $errorMsgOutput.$msg;
}
// 返回的是Json格式的內容,便於客戶端解析
echo '{"success":"'.($uploadOk == 1 ? 'true': 'false').'","url":"'.$target_file_unique.'","errorMsg":"'.$errorMsgOutput.'"}';
?>
備注:
遇到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/images
sudo chmod 0755 /usr/share/nginx/images
解決跨域的問題
由於是獨立的靜態文件服務器,所以必定會遇到跨域上傳的問題,可以這樣解決:
第一步:
sudo vim /etc/nginx/conf.d/default.conf
添加以下配置:
location ~ \.(png|gif|jpg|jpeg)$ {
...
...
add_header Access-Control-Allow-Origin *; // 添加這一行配置
...
...
}
第二步:
做Nginx根目錄下添加文件:crossdomain.xml
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
在瀏覽器里直接訪問:http://url/crossdomain.xml
訪問該文件,可以正常訪問即可。
以Uplodify為例:
沒有增加跨域配置之前:
如果使用uploadify上傳文件,可以做Chrome的開發者工具里看到以下信息:
Uploadify頁面上會顯示如下錯誤:
修改配置之后,從Fiddle可以看到上傳已經成功,返回了正確的Json:
[CentOS 6上用Nginx搭建靜態文件站的方法]http://www.cnblogs.com/wushangjue/p/5289095.html