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

posted @ 2016-03-18 09:39  无上@诀  阅读(2957)  评论(0编辑  收藏  举报