nginx服务器提供静态资源的配置

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/f2764052703/article/details/90579908

一、创建静态资源存放的目录

First, create the /data/www directory and put an index.html file with any text content into it and create the /data/images directory and place some images in it.

首先,我们要创建一个存放HTML文件的目录,以及存放图片的目录,然后我们在里面放置一些测试的文件。


二、在nginx配置文件中对nginx进行配置

Next, open the configuration file. The default configuration file already includes several examples of the server block, mostly commented out. For now comment out all such blocks and start a new server block:

在nginx/conf/nginx.fonf文件中对静态资源的路径进行配置。
在nginx配置文件中一般都会为我们配置一个基本的文件,其中包含了这样的一个块:

http {
	server {
	}
}

这里的块是一个基本的nginx配置块,其中server这个块是配置了每一个服务器的名字和他们监听的端口,一旦nginx将请求匹配到对应的服务器,它就会根据服务器内定义的位置的参数测试请求头中指定的URI。

location / {
    root /data/www;
}

location块定义了URL匹配的资源路径,也就是说它定义了URL路径与物理路径的映射。

This location block specifies the “/” prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is, to /data/www, to form the path to the requested file on the local file system. If there are several matching location blocks nginx selects the one with the longest prefix. The location block above provides the shortest prefix, of length one, and so only if all other location blocks fail to provide a match, this block will be used.

当有一个请求访问到这个服务器的时候,它会优先匹配最长的URL,如果说所有的URL都不满足的话,他就会匹配长度为1的URL,即匹配根节点。



从浏览器中访问静态资源

这里是我的一个nginx配置文件中的信息,server配置了服务器的相关设置,location配置了URL映射,在最后从外部文件夹中引入了一段配置信息。

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

    sendfile        on;
  
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        
        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    include vhost/*.conf;
}

在vhost文件夹下面我创建了一个image.conf的文件
image.conf

server {
    listen 80;
    autoindex off;
    server_name image
    access_log c:/access.log combined;
    index index.html index.htm index.jsp index.php;
    #error_page 404 /404.html;
    if ( $query_string ~* ".*[\;'\<\>].*" ){
        return 404;
    }

    location ~ /(mmall_fe|mmall_admin_fe)/dist/view/* {
        deny all;
    }
 
    location / {
        root C:\ftpfile\img;
        add_header Access-Control-Allow-Origin *;
    }
}

image服务器为服务提供了图片资源,图片资源都是在C:\ftpfile\img文件夹下。

C:\ftpfile\img文件夹下我预先放好了一个名字为11.jpg的图片。



三、将设置加载到nginx服务器中

如果已经配置nginx环境变量:nginx -s reload

没有配置nginx环境变量:在nginx.exe的文件夹下进入命令行,使用nginx.exe -s reload进行加载



四、从浏览器访问图片资源

打开浏览器,输入http://image/11.jpg即可访问到这张图片

猜你喜欢

转载自blog.csdn.net/f2764052703/article/details/90579908