Nginx常见应用场景


本教程讲述 Nginx 的常见应用场景。内容接上文:Nginx基本配置

前提:假设我们已经安装好了 Nginx,并启动成功。

场景一:代理静态文件

Nginx 一个常用的功能是用来配置静态文件的代理服务器。其实默认配置,已经是个静态文件的代理服务器的配置了。这里我们重点关注 /etc/nginx/conf.d/default.conf:

server {
    listen       80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

第一个 location 块:

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
}

这里会把所有请求的文件在 /usr/share/nginx/html 文件夹下进行搜索,并将匹配的内容进行返回。我们可以尝试在/usr/share/nginx/html 文件夹下新增一个 test.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Test</title>
</head>
<body>
    Hello World!
</body>
</html>

然后浏览器访问 http://localhost:80/test.html

Nginx 代理静态文件测试页面

可以成功看到如上页面,代表 Nginx 代理文件成功。Nginx 不仅仅可以代理 HTML,还可以代理其他多种类型的文件,比如 CSS,JavaScript,和图片等。

场景二:代理服务器

Nginx 另一个常用的功能是用来配置应用程序的代理服务器(即反向代理,后续会详细说明这个概念)。这里我们直接使用 DummyJSON 作为要被代理的服务。DummyJSON 提供了多个可以直接使用的 API,方便开发者开发调试使用。

我们先在 Nginx 配置目录 conf.d 下新建一个 api.conf

server {
    listen       8001;
    server_name  localhost;

    location / {
        proxy_pass http://dummyjson.com;
    }
}

这里创建了一个虚拟的 Server,监听8001端口,通过 proxy_pass,将该端口收到的请求转发到 http://dummyjson.com,从而完成对 DummyJSON 服务的代理。重新加载 Nginx,使新配置文件生效:

nginx -s reload

通过 Postman 调用 http://localhost:8001/products,如果成功,可以看到如下返回结果:

代理 DummyJSON 服务

注意,如果是通过 Docker 启动的 Nginx,需要将 8001 端口暴露出去,才可以在主机的浏览器内访问:

docker run --rm -p 80:80 -p 8001:8001 -it centos7-nginx-demo:local bash
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值