12.16 Nginx代理

时间:2022-04-27
本文章向大家介绍12.16 Nginx代理,主要内容包括Nginx代理目录概要、Nginx代理、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Nginx代理目录概要

  • cd /usr/local/nginx/conf/vhost
  • vim proxy.conf //加入如下内容
server
{
    listen 80;
    server_name ask.apelearn.com;

    location /
    {
        proxy_pass      http://121.201.9.155/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Nginx代理

  • 需求:
    • 用户需要访问web服务器,但用户因为各种原因没办法访问或者访问很慢(私网无访问、境内访问国外服务器),所以,就需要一个能访问web服务器的代理者,让用户通过代理服务器访问
  • 解决方法
    • 创建代理服务器
  1. 首先切换目录cd /usr/local/nginx/conf/vhost
[root@hanfeng ~]# cd /usr/local/nginx/conf/vhost
[root@hanfeng vhost]# 
  1. 新建一个配置文件vim proxy.conf
[root@hanfeng vhost]# vim proxy.conf

加入以下内容
server
{
    listen 80;
    server_name ask.apelearn.com;                       //定义域名,论坛的网站
    location /
    {
        proxy_pass      http://121.201.9.155/;         //定义域名,论坛的IP
        proxy_set_header Host   $host;                   //定义访问的域名 为 $host =server_name ask.apelearn.com
        proxy_set_header X-Real-IP      $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
保存退出
  1. 配置文件中,没有了root,因为这是一个代理服务器,它不需要访问本地服务器上的任何文件
  2. 在配置完成后,这台虚拟机就可以访问ask.apelearn.com论坛了
  3. 检查配置文件语法错误,并重新加载配置文件
[root@hanfeng vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@hanfeng vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@hanfeng vhost]# 
  1. robots是针对蜘蛛的索引的一个列表,一般网站都会有robots
[root@hanfeng vhost]# curl ask.apelearn.com/robots.txt
#
# robots.txt for MiWen
#

User-agent: *

Disallow: /?/admin/
Disallow: /?/people/
Disallow: /?/question/
Disallow: /account/
Disallow: /app/
Disallow: /cache/
Disallow: /install/
Disallow: /models/
Disallow: /crond/run/
Disallow: /search/
Disallow: /static/
Disallow: /setting/
Disallow: /system/
Disallow: /tmp/
Disallow: /themes/
Disallow: /uploads/
Disallow: /url-*
Disallow: /views/
Disallow: /*/ajax/[root@hanfeng vhost]# 
[root@hanfeng vhost]# 
  1. 测试代理是否成功,指定本机的IP,也能去访问
[root@hanfeng vhost]# curl -x127.0.0.1:80  ask.apelearn.com/robots.txt
#
# robots.txt for MiWen
#

User-agent: *

Disallow: /?/admin/
Disallow: /?/people/
Disallow: /?/question/
Disallow: /account/
Disallow: /app/
Disallow: /cache/
Disallow: /install/
Disallow: /models/
Disallow: /crond/run/
Disallow: /search/
Disallow: /static/
Disallow: /setting/
Disallow: /system/
Disallow: /tmp/
Disallow: /themes/
Disallow: /uploads/
Disallow: /url-*
Disallow: /views/
Disallow: /*/ajax/[root@hanfeng vhost]# 
  1. 正常情况下,不去配置这个代理,是不可能通过本地访问到远程的站点的