Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案

环境CentOS6.9 Nginx 1.14.0 (centos7命令会有所不同)

课程目标

1:Nginx的安装

2:文件服务器的搭建

3:Ftp远程文件上传实现

4:文件静态化上传到指定的文件服务器

5:总结

Nginx 的安装

1 :安装依赖
yum install wget gcc gcc-c++ pcre pcre-devel openssl openssl-devel zlib zlib-devel
2:创建nginx启动用户
> /usr/sbin/groupadd -f www ---建立用户组 www
> /usr/sbin/useradd -g www www ---添加用户 www
会在/home目录生成对应www的用户目录,root/www才能被访问
3:下载nginx

下载地址:<http://nginx.org/en/download.html

> cd /usr/local/src
> wget http://nginx.org/download/nginx-1.14.0.tar.gz
4:解压缩编译安装
> tar zxf nginx-1.14.0.tar.gz
> cd nginx-1.14.0
> ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module
> make
> make install
5:设置nginx软链接或自行添加环境变量
ln -sv /usr/local/nginx/sbin/nginx /usr/local/sbin/
6:配置nginx服务并设置开机启动
# 设置service启动的方式
wget -P /etc/init.d/ http://down.whsir.com/downloads/nginx
chmod +x /etc/init.d/nginx

# 设置开机自启动
chkconfig --add nginx
chkconfig nginx on
7:启动nginx
> /etc/init.d/nginx start 启动
> service nginx start 启动
> service nginx stop 停止
> service nginx restart 重启
> service nginx status 查看nginx的经常状态
8:添加环境变量(意思:就是任意目录下执行 nginx命令都有效)
最后访问http://IP即可看到nginx欢迎页,默认欢迎页面在/usr/local/nginx/html目录下
附:添加环境变量方法

> vi /etc/profile
添加以下内容
> export PATH=$PATH:/usr/local/nginx/sbin
保存退出,执行以下命令使其生效
> source /etc/profile
9:关闭防火墙
> service iptables stop
> chkconfig iptables off 
10 : 访问

http://192.168.189.129/

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

恭喜你nginx安装成功!

文件服务器的搭建

1:修改nginx.conf 文件设置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        
        
	    location /pages {
          alias /home/www/pages;
          autoindex on;
        }


    }
   

}

#核心代码,搭建文件服务器指定的目录

location /pages {
alias /home/www/pages;
autoindex on;
}

浏览器:

如果在浏览器中去访问一个web服务器的资源目录,那么浏览器会自动去当前资源目录中查找index.html页面

<http://192.168.31.130:8989/pages===<http://192.168.31.130:8989/pages/index.html

Ftp远程文件上传实现

Ftp服务器的安装

前提

ssh服务已经开启,关闭防火墙,主机和虚拟机能ping通

查看ssh和防火墙的状态

​ service sshd status

​ service iptables status

开启ssh服务

​ service sshd start

关闭防火墙

​ chkconfig iptables off

测试主机和虚拟机的连通性

ping 192.168.189.129

安装并开启tftp和vsftpd

root@localhost ~]# yum install tftp

[root@localhost ~]# yum install vsftpd

[root@localhost ~]# chkconfig vsftpd on

[root@localhost ~]# chkconfig tftp on

启动vsftpd 服务

service vsftpd start

查看vsftpd 的启动状态

service vsftpd status

打开21和20端口

[root@localhost ~]# /sbin/iptables -I INPUT -p tcp –dport 21 -j ACCEPT

[root@localhost ~]# /sbin/iptables -I INPUT -p tcp –dport 20 -j ACCEPT

[root@localhost ~]# /etc/rc.d/init.d/iptables save

《Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案》 

添加ftp用户

[root@localhost vsftpd]# cd /etc/vsftpd

[root@localhost vsftpd]# useradd ftpuser

[root@localhost vsftpd]# passwd ftpuser

修改sftpd .conf配置文件

[root@localhost vsftpd]#vi /etc/vsftpd/vsftpd.conf

把第一行的 anonymous_enable=YES ,改为NO

重启vstfpd 服务
[root@localhost upload]# service vsftpd restart
windows cmd测试链接
C:\Users\Administrator>ftp 192.168.1.112

连接到 192.168.1.112。

220 (vsFTPd 2.2.2)

用户(192.168.1.112:(none)): ftpuser

331 Please specify the password.

密码:

500 OOPS: cannot change directory:/home/ftpuser

登录失败。

ftp> bye

可以看到报了个错误:500 OOPS: cannot change directory:/home/ftpuser。原因是CentOS系统安装了SELinux,因为默认下是没有开启FTP的支持,所以访问时都被阻止了。查看如下:

[root@localhost vsftpd]# getsebool -a | grep ftp

allow_ftpd_anon_write –> off

allow_ftpd_full_access –> off

allow_ftpd_use_cifs –> off

allow_ftpd_use_nfs –> off

ftp_home_dir –> off

ftpd_connect_db –> off

httpd_enable_ftp_server –> off

tftp_anon_write –> off

[root@localhost vsftpd]#

只要把allow_ftpd_full_access –> off,ftp_home_dir –> off改为on就可以了。

[root@localhost vsftpd]# setsebool ftp_home_dir 1
[root@localhost vsftpd]# setsebool allow_ftpd_full_access 1
开启SELinux

如执行getsebool -a | grep ftp出现getsebool: SELinux is disabled的错误,需重新开启selinux

《Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案》

vi /etc/selinux/config
更改为:SELINUX=enabled

必须重启linux,不重启是没办法立刻开启selinux的

重启完以后,就可以使用getsebool -a | grep ftp命令了

再次查看

[root@localhost vsftpd]# getsebool -a | grep ftp

allow_ftpd_anon_write –> off

allow_ftpd_full_access –> on

allow_ftpd_use_cifs –> off

allow_ftpd_use_nfs –> off

ftp_home_dir –> on

ftpd_connect_db –> off

httpd_enable_ftp_server –> off

tftp_anon_write –> off

再次测试连接

C:\Users\Administrator>ftp 192.168.1.112

连接到 192.168.1.112。

220 (vsFTPd 2.2.2)

用户(192.168.1.112:(none)): ftpuser

331 Please specify the password.

密码:

230 Login successful.

ftp> ls

200 PORT command successful. Consider using PASV.

150 Here comes the directory listing.

226 Directory send OK.

ftp> bye

221 Goodbye.

Ok,配置成功,可以用flashxftp来进行上传文件了。

Flashxftp上传文件

首先在/home的目录中创建一个目录,然后设置权限为777 《Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案》

[root@localhost home]# mkdir /home/www/pages

[root@localhost upload]# chmod -R 777 /home/www

然后修改vsftp的配置文件vsftpd.conf文件

[root@localhost upload]# vi /etc/vsftpd/vsftpd.conf

在最后添加上

local_root=/home/www 保存,

然后重启vsftpd服务器程序。

service vsftpd restart

配置完成,就可以通过ftp上传文件到/home/www/pages目录下了。

FTP客户端的调用测试

1:引入依赖pom.xml

 <!--ftp-->
 <dependency>
     <groupId>commons-net</groupId>
     <artifactId>commons-net</artifactId>
     <version>3.6</version>
 </dependency>

2:定义工具类

package com.itbooking.util;

import org.apache.commons.net.ftp.*;

import java.io.*;
import java.net.*;

public class FTPUtils { 

   //ftp服务器地址
   private String hostname = "192.168.189.129";
   //ftp服务器端口号默认为21
   private Integer port = 21 ;
   //ftp登录账号
   private String username = "ftpuser";
   //ftp登录密码
   private String password = "mkxiaoer";

   private FTPClient ftpClient = null;

    private static String encoding = System.getProperty("file.encoding");
    
    
    public static void main(String[] args) throws IOException { 
        FTPUtils fi = new FTPUtils();
        fi.initFtpClient();
        //fi.createDirecroty("2019");
        boolean flag = fi.uploadFile("/home/www/pages","39oij92po3j4234242423.html","d://d.html");
        System.out.println(flag);
    }
    

   /** * 初始化ftp服务器 */
   private void initFtpClient() { 
       ftpClient = new FTPClient();
       ftpClient.setControlEncoding("utf-8");
       try { 
           ftpClient.connect(hostname, port); //连接ftp服务器
           ftpClient.login(username, password);//登录ftp服务器
           ftpClient.enterLocalPassiveMode();//文件上传成功 但是内容为空 需要加上
           ftpClient.setControlEncoding(encoding);
           ftpClient.getReplyCode(); //是否成功登录服务器
       } catch (MalformedURLException e) { 
           e.printStackTrace();
       } catch (IOException e) { 
           e.printStackTrace();
       }
   }


   /** * 上传文件 * * @param pathname ftp服务保存地址 * @param fileName 上传到ftp的文件名 * @param originfilename 待上传文件的名称(绝对地址) * * @return */
   public boolean uploadFile(String pathname, String fileName, String originfilename) { 
       boolean flag = false;
       InputStream inputStream = null;
       try { 
           inputStream = new FileInputStream(new File(originfilename));
           initFtpClient();
           ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
           if (!existFile(pathname)) { 
               createDirecroty(pathname);
           }
           ftpClient.changeWorkingDirectory(pathname);
           flag = ftpClient.storeFile(fileName, inputStream);
       } catch (Exception e) { 
           e.printStackTrace();
       } finally { 
           try { 
               ftpClient.logout();
           } catch (IOException e) { 
               e.printStackTrace();
           }
           if (ftpClient.isConnected()) { 
               try { 
                   ftpClient.disconnect();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
           if (null != inputStream) { 
               try { 
                   inputStream.close();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
       }
       return flag;
   }

   /** * 上传文件 * * @param pathname ftp服务保存地址 * @param fileName 上传到ftp的文件名 * @param inputStream 输入文件流 * @return */
   public boolean uploadFile(String pathname, String fileName, InputStream inputStream) { 
       boolean flag = false;
       try { 
           initFtpClient();
           ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
           if (!existFile(pathname)) { 
               createDirecroty(pathname);
           }
           ftpClient.changeWorkingDirectory(pathname);
           ftpClient.storeFile(fileName, inputStream);
           inputStream.close();
           ftpClient.logout();
           flag = true;
       } catch (Exception e) { 
           e.printStackTrace();
       } finally { 
           if (ftpClient.isConnected()) { 
               try { 
                   ftpClient.disconnect();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
           if (null != inputStream) { 
               try { 
                   inputStream.close();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
       }
       return true;
   }

   //改变目录路径
   public boolean changeWorkingDirectory(String directory) { 
       boolean flag = true;
       try { 
           flag = ftpClient.changeWorkingDirectory(directory);
           if (flag) { 
               System.out.println("进入文件夹" + directory + " 成功!");

           } else { 
               System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
           }
       } catch (IOException ioe) { 
           ioe.printStackTrace();
       }
       return flag;
   }

   //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
   public boolean createDirecroty(String remote) throws IOException { 
       String directory = remote + "/";
       // 如果远程目录不存在,则递归创建远程服务器目录
       if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) { 
           int start = 0;
           int end = 0;
           if (directory.startsWith("/")) { 
               start = 1;
           }
           end = directory.indexOf("/", start);
           String path = "";
           StringBuilder paths = new StringBuilder();
           while (true) { 
               String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
               path = path + "/" + subDirectory;
               if (!existFile(path)) { 
                   if (makeDirectory(subDirectory)) { 
                       changeWorkingDirectory(subDirectory);
                   } else { 
                       System.out.println("创建目录[" + subDirectory + "]失败");
                       changeWorkingDirectory(subDirectory);
                   }
               } else { 
                   changeWorkingDirectory(subDirectory);
               }
               paths.append("/").append(subDirectory);
               start = end + 1;
               end = directory.indexOf("/", start);
               // 检查所有目录是否创建完毕
               if (end <= start) { 
                   break;
               }
           }
       }
       return true;
   }

   //判断ftp服务器文件是否存在
   public boolean existFile(String path) throws IOException { 
       boolean flag = false;
       FTPFile[] ftpFileArr = ftpClient.listFiles(path);
       if (ftpFileArr.length > 0) { 
           flag = true;
       }
       return flag;
   }

   //创建目录
   public boolean makeDirectory(String dir) { 
       boolean flag = true;
       try { 
           flag = ftpClient.makeDirectory(dir);
       } catch (Exception e) { 
           e.printStackTrace();
       }
       return flag;
   }

   /** * 下载文件 * * * @param pathname FTP服务器文件目录 * * @param filename 文件名称 * * @param localpath 下载后的文件路径 * * @return */
   public boolean downloadFile(String pathname, String filename, String localpath) { 
       boolean flag = false;
       OutputStream os = null;
       try { 
           initFtpClient();
           //切换FTP目录
           ftpClient.changeWorkingDirectory(pathname);
           FTPFile[] ftpFiles = ftpClient.listFiles();
           for (FTPFile file : ftpFiles) { 
               if (filename.equalsIgnoreCase(file.getName())) { 
                   File localFile = new File(localpath + "/" + file.getName());
                   os = new FileOutputStream(localFile);
                   ftpClient.retrieveFile(file.getName(), os);
                   os.close();
               }
           }
           ftpClient.logout();
           flag = true;
       } catch (Exception e) { 
           e.printStackTrace();
       } finally { 
           if (ftpClient.isConnected()) { 
               try { 
                   ftpClient.disconnect();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
           if (null != os) { 
               try { 
                   os.close();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
       }
       return flag;
   }

   /** * 删除文件 * * * @param pathname FTP服务器保存目录 * * @param filename 要删除的文件名称 * * @return */
   public boolean deleteFile(String pathname, String filename) { 
       boolean flag = false;
       try { 
           initFtpClient();
           //切换FTP目录
           ftpClient.changeWorkingDirectory(pathname);
           ftpClient.dele(filename);
           ftpClient.logout();
           flag = true;
       } catch (Exception e) { 
           e.printStackTrace();
       } finally { 
           if (ftpClient.isConnected()) { 
               try { 
                   ftpClient.disconnect();
               } catch (IOException e) { 
                   e.printStackTrace();
               }
           }
       }
       return flag;
   }
}

请注意:在进行ftp远程文件上传的时候,不需要在指明/home/www/pages目录了,因子在vsftpd.conf文件中以及配置指明了.

文件静态化上传到指定的文件服务器

关于商品添加的指令

1:改造文件静态化上传到远程服务器

 // Ftp文件上传
            String dataPath = dateFinshPath.replaceAll("pages\\/","");
            boolean flag =  new FTPUtils().uploadFile(dataPath,fileName,targetFile.getAbsolutePath());
            String url = dateFinshPath+fileName;
            if(flag){ 
                //更新数据库url,如果你静态资源和静态化资源要经常迁移,建议把服务器路径和资源分开存储。
                System.out.println("ftp 上传成功---静态化成功================>"+url);
                //MQ 广播去修改地址和状态
                //iItemService.updateItemUrl();
                Map<String,Object> params = new HashMap<>();
                params.put("itemId",itemId);
                params.put("url","http://192.168.189.129/"+url);
                jmsMessagingTemplate.convertAndSend(new ActiveMQTopic("mq.freemaker.static.update.url"),JsonUtil.obj2String(params));
                targetFile.delete();
                //8.关闭Writer对象
            }else{ 
                System.out.println("静态化失败================>"+url);
            }

2:MQ调用修改商品的链接地址信息

  jmsMessagingTemplate.convertAndSend(new ActiveMQTopic("mq.freemaker.static.update.url"),JsonUtil.obj2String(params));

3:将静态资源文件上传至文件服务器,“/home/www/pages”目录下即可。

4:预览查询看效果。

《Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案》

《Nginx文件服务器的搭建(完整安装过程) + Ftp远程文件上传解决方案》

关于修改触发的指令

关于删除触发的指令

    原文作者:谔定靴
    原文地址: https://blog.csdn.net/qq_42734859/article/details/89946733
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞