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

<?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:


[參考文章]https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-centos-7


免責聲明!

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



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