Linux下nginx的安装和使用(CentOS6.5为例)

10 篇文章 0 订阅

安装环境

nginx是C语言开发,建议在linux上运行,本教程使用Centos6.5作为安装环境。

  • gcc

    安装nginx需要先将官网下载的源码进行编译,编译依赖gcc环境,如果没有gcc环境,需要安装gcc:

    yum install gcc-c++

  • PCRE

    PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括 perl 兼容的正则表达式库。nginx的http模块使用pcre来解析正则表达式,所以需要在linux上安装pcre库。

    yum install -y pcre pcre-devel

  • zlib

    zlib库提供了很多种压缩和解压缩的方式,nginx使用zlib对http包的内容进行gzip,所以需要在linux上安装zlib库。

    yum install -y zlib zlib-devel

  • openssl

    OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。nginx不仅支持http协议,还支持https(即在ssl协议上传输http),所以需要在linux安装openssl库。

    yum install -y openssl openssl-devel

编译安装

将下载好的Linux版本的nginx压缩包上传到Linux服务器的/usr/local/src下

解压:

tar -zxvf nginx-1.8.0.tar.gz

其中,z代表压缩的格式,x代表压缩,v表示显示进度,f是后面接要压缩的文件名

cd nginx-1.8.0

接着我们需要设置编译参数,进入nginx后执行以下代码

./configure \
--prefix=/usr/local/nginx \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi

注意:上边将临时文件目录指定为/var/temp/nginx,需要在/var下创建temp及nginx目录

完成后我们会得到Makefile文件夹

image-20200519114146624

编译:make

安装:make install

我们在上面参数中设置了安装到/usr/local/nginx文件夹中

安装成功查看安装目录 :

img

nginx使用

启动nginx

cd /usr/local/nginx/sbin/
./nginx 

这时候,我们可以通过ip访问查看是否成功启动,由于nginx默认是80端口,我们之间在浏览器输入ip不需要添加端口号即可查看

很不幸,打不开链接,下面进行原因排查:

说明服务器的80端口是打不开的。

我们需要手动打开80端口

/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT

将打开的端口的访问规则保存在文件中

/etc/rc.d/init.d/iptables save

查看机器开放的端口号

/etc/init.d/iptables status

image-20200519114933547

这时候,我们再次刷新浏览器就可以发现nginx启动了

image-20200519115025566

停止nginx

方式1,快速停止:

cd /usr/local/nginx/sbin

./nginx -s stop

此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。

方式2,完整停止(建议使用):

cd /usr/local/nginx/sbin

./nginx -s quit

此方式停止步骤是待nginx进程处理任务完毕进行停止。

重启nginx

方式1,先停止再启动(建议使用):

对nginx进行重启相当于先停止nginx再启动nginx,即先执行停止命令再执行启动命令。

如下:

./nginx -s quit

./nginx

方式2,重新加载配置文件:

当nginx的配置文件nginx.conf修改后,要想让配置生效需要重启nginx,使用-s reload不用先停止nginx再启动nginx即可将配置信息在nginx中生效,如下:

./nginx -s reload

开机自启

在/etc/init.d/目录下创建nginx文件

vi /etc/init.d/nginx

在脚本中添加如下命令:

#!/bin/bash

# nginx Startup script for the Nginx HTTP Server

# it is v.0.0.2 version.

# chkconfig: - 85 15

# description: Nginx is a high-performance web and proxy server.

#              It has a lot of features, but it's not for everyone.

# processname: nginx

# pidfile: /var/run/nginx.pid

# config: /usr/local/nginx/conf/nginx.conf

nginxd=/usr/local/nginx/sbin/nginx

nginx_config=/usr/local/nginx/conf/nginx.conf

nginx_pid=/var/run/nginx.pid

RETVAL=0

prog="nginx"

# Source function library.

. /etc/rc.d/init.d/functions

# Source networking configuration.

. /etc/sysconfig/network

# Check that networking is up.

[ ${NETWORKING} = "no" ] && exit 0

[ -x $nginxd ] || exit 0

# Start nginx daemons functions.

start() {

if [ -e $nginx_pid ];then

   echo "nginx already running...."

   exit 1

fi

   echo -n $"Starting $prog: "

   daemon $nginxd -c ${nginx_config}

   RETVAL=$?

   echo

   [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx

   return $RETVAL

}

# Stop nginx daemons functions.

stop() {

        echo -n $"Stopping $prog: "

        killproc $nginxd

        RETVAL=$?

        echo

        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid

}

# reload nginx service functions.

reload() {

    echo -n $"Reloading $prog: "

    #kill -HUP `cat ${nginx_pid}`

    killproc $nginxd -HUP

    RETVAL=$?

    echo

}

# See how we were called.

case "$1" in

start)

        start

        ;;

stop)

        stop

        ;;

reload)

        reload

        ;;

restart)

        stop

        start

        ;;

status)

        status $prog

        RETVAL=$?

        ;;

*)

        echo $"Usage: $prog {start|stop|restart|reload|status|help}"

        exit 1

esac

exit $RETVAL

设置/etc/init.d/nginx 执行权限

chmod 777 /etc/init.d/nginx

设置开机默认启动

chkconfig --add nginx //添加系统服务
chkconfig --level 345 nginx on //设置开机启动,启动级别
chkconfig --list nginx //查看开机启动配置信息

nginx搭建图片服务器

在vsftpd组件安装完成后,我们可以通过nginx搭建服务器,安装vsftpd详细步骤在另一篇博客《Linux安装ftp组件(CentOS6.5为例)》

配置图片存放,访问路径

vim /usr/local/nginx/conf/nginx.conf

image-20200519160912012

修改完成后,进入到/usr/local/nginx/sbin 目录下,重新启动nginx服务器

./nginx -s reload

修改用户访问权限

这时候我们查看上传的图片会报403Forbidden错误,简单的理解为没有权限访问此站,因此我们还需要修改用户访问权限

chown ftpadmin /home/ftpadmin`

chmod 777 -R /home/ftpadmin

上传

这时候我们就可以通过工具将要上传的图片上传到/home/ftpuser/www/images下面

image-20200519161334350

然后可以直接在地址后面加/images/上传名就可以访问了

image-20200519161420189

Java代码访问ftp服务器

使用apache的FTPClient工具访问ftp服务器。需要在pom文件中添加依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>${commons-net.version}</version>
</dependency>
public class FtpClientTest {
	@Test
	public void testFtp() throws Exception{
		//连接ftp服务器
		FTPClient ftpClient = new FTPClient();
		//默认是21端口,不写也行
		ftpClient.connect("192.168.10.130", 21);
		//登陆ftp服务器
		ftpClient.login("ftpuser", "ftpuser");
		//上传文件
		//读取本地文件
		FileInputStream inputStream = new FileInputStream(new File("D:\\1.jpg"));
		//设置上传的路径
		ftpClient.changeWorkingDirectory("/home/ftpuser/www/images");
		//修改上传文件格式,因为win默认图片是二进制格式,而上传默认是文本格式
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		//第一个参数:服务器文档名
		//第二个参数:上传文件的InputStream
		ftpClient.storeFile("hello1.jpg", inputStream);
		//关闭连接
		ftpClient.logout();
	}
}

封装成工具类

package com.taotao.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * ftp上传下载工具类
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 
 * @author	JY
 * @date	2020年5月19日下午3:11:51
 * @version 1.0
 */
public class FtpUtil {

	/** 
	 * Description: 向FTP服务器上传文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param basePath FTP服务器基础目录
	 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
	 * @param filename 上传到FTP服务器上的文件名 
	 * @param input 输入流 
	 * @return 成功返回true,否则返回false 
	 */  
	public static boolean uploadFile(String host, int port, String username, String password, String basePath,
			String filePath, String filename, InputStream input) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);// 连接FTP服务器
			// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			//切换到上传目录
			if (!ftp.changeWorkingDirectory(basePath+filePath)) {
				//如果目录不存在创建目录
				String[] dirs = filePath.split("/");
				String tempPath = basePath;
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) continue;
					tempPath += "/" + dir;
					if (!ftp.changeWorkingDirectory(tempPath)) {
						if (!ftp.makeDirectory(tempPath)) {
							return result;
						} else {
							ftp.changeWorkingDirectory(tempPath);
						}
					}
				}
			}
			//设置上传文件的类型为二进制类型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			//上传文件
			if (!ftp.storeFile(filename, input)) {
				return result;
			}
			input.close();
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	/** 
	 * Description: 从FTP服务器下载文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param remotePath FTP服务器上的相对路径 
	 * @param fileName 要下载的文件名 
	 * @param localPath 下载后保存到本地的路径 
	 * @return 
	 */  
	public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
			String fileName, String localPath) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);
			// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());

					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}

			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		try {  
	        FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));  
	        boolean flag = uploadFile("192.168.10.130", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);  
	        System.out.println(flag);  
	    } catch (FileNotFoundException e) {  
	        e.printStackTrace();  
	    }  
	}
}

image-20200519161834258

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值