阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

CentOS 6(64-bit) + Nginx搭建静态文件服务器

117次阅读
没有评论

共计 4219 个字符,预计需要花费 11 分钟才能阅读完成。

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 的文件名存储起来
functionGUID(){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 的开发者工具里看到以下信息:
CentOS 6(64-bit)+ Nginx 搭建静态文件服务器

Uploadify 页面上会显示如下错误:

CentOS 6(64-bit)+ Nginx 搭建静态文件服务器

修改配置之后,从 Fiddle 可以看到上传已经成功,返回了正确的 Json:

CentOS 6(64-bit)+ Nginx 搭建静态文件服务器

 

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-01/139196.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计4219字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中