Nginx搭建文件下载服务器

一、在本机搭建文件服务器

1、修改配置文件:

server {
    listen       80;
    server_name  localhost;
    #防止乱码,需要加上编码
    #charset utf-8;
    #路由规则
    #如果想把nginx作为下载服务器,则改为系统目录地址
    #比如下面这样,(1)当访问主页时,打开的是本地的/data/upload/file目录
    location / {
        root   /data/upload/file;
        autoindex on;    #开启索引功能
        autoindex_exact_size off;  #关闭计算文件确切大小(单位bytes),
                                   #只显示大概大小(单位kb、mb、gb)
        charset 'utf-8'; #防止乱码,需要加上编码
        autoindex_localtime on;   #显示本机时间而非 GMT 时间
    }

    #location /file/ {     
		#root /data/icp/upload/;
		#charset 'utf-8';
		#autoindex on;
	#}
   
}

2、修改好配置文件后,创建相对应的目录

3、重启nginx,访问页面http://localhost:80/

注意:如果访问页面报403的错误,这个是因为权限的问题,首先这里我们修改了启动nginx的用户为root,root的最高权限账户,所以不存在用户权限的问题,那么这里的权限问题就是SELINUX导致的,把它禁用了就可以了。方法是修改配置文件”/etc/selinux/config”,如下:

《Nginx搭建文件下载服务器》

4、.当需要配置多个访问路径的时候,则其他的路径要将root改为alias:

	location /test {
        alias   /nginx/html/;#这里应该是alias,不再是root
        index   index.html;
    }

二、Nginx访问另一台服务器上的文件 

(一) 方法一

A服务器访问B服务器目录下的文件

1、两台服务器都需要安装nginx,且nginx配置如下:

A服务器配置:

#给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配
location ^~ /file/{
		try_files $uri @new_uploads;
}
location @new_uploads{
		proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://xxx.xx.xxx.xxx:9012;
}

B服务器配置:

server {
        listen       9012;
        server_name  localhost;
		location ^~ /file/{
			alias  /home/file/;
			#autoindex on;(原配置)
            autoindex on;
			index  index.html index.htm;
		}
     }

2、重启两台服务器的nginx

3、访问:A服务器IP:端口/file/xxx即可访问到B服务器/home/file/目录下的文件了。

(二)方法二

A服务器访问B服务器目录下的文件

1、两台服务器都需要安装nginx,且nginx配置如下:

A服务器配置:

location /file{
	proxy_pass http://172.16.42.100:8081/file;
	 client_max_body_size 5000m;
}

B服务器配置:

server {
        listen       8081;
        server_name  localhost;
		 location  /file {     
			root /data/icp/upload;
			charset 'utf-8';
			autoindex on;
			index  index.html index.htm;
		}
     }

2、重启两台服务器的nginx

3、访问:A服务器IP:端口/file/xxx即可访问到B服务器/data/icp/upload/file/目录下的文件了。

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