• Ubuntu 14.04TLS Nginx搭建静态文件服务器


    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

  • 相关阅读:
    Redis主从复制
    Centos6克隆虚拟机改IP和mac地址
    Liunx中ERROR 2002 (HY000) Can't connect to local MySQL server through socket 'varlibmysqlmysql.sock' (2)报错
    linux安装redis
    每天五分钟带你了解Redis
    sqiud --ACL控制应用、sarg日志分析、反向代理
    squid--透明代理
    Squid--传统代理
    Tomcat+Nginx实现动静分离
    -bash: nginx: 未找到命令/没有这个文件
  • 原文地址:https://www.cnblogs.com/wushangjue/p/5287553.html
Copyright © 2020-2023  润新知