在Debian/Ubuntu VPS下配置Nginx做反向代理

Debian和Ubuntu都自带了Nginx,用他们来配置Nginx的反向代理,非常方便。

安装Nginx

运行如下命令安装并运行Nginxapt-get install nginx
/etc/init.d/nginx start
然后在浏览器里面访问该IP的80端口,就会看到"Welcome to Nginx!"的信息,这说明Nginx安装完成了!

配置Nginx做反向代理

Nginx的缺省站点的配置文件是/etc/nginx/sites-available/default,修改这个文件中的如下部分:
        location / {
               root   /var/www/nginx-default;
               index  index.html index.htm;
        }
修改为:
        location / {
            proxy_pass http://www.google.com/;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
然后重启Nginx:/etc/init.d/nginx restart然后在浏览器里面重新访问该IP上面的80端口,应该就看到google的主页了,反向代理配置成功了

多域名反向代理配置实例

在一个VPS上配置多个域名的反向代理,比如我们有两个域名test1.rashost.com和test2.rashost.com,我们希望客户在访问test1.rashost.com的时候出现www.baidu.com的内容,希望客户在访问test2.rashost.com的时候出现www.kernel.org的内容,客户只知道test1.rashost.com和test2.rashost.com的存在,而不知道www.baidu.comwww.kernel.org的存在。首先需要把域名test1.rashost.com和test2.rashost.com指向VPS的IP地址。然后在/etc/nginx/sites-available 目录下增加两个文件,文件名分别是test1.rashost.com和test2.rashost.comtest1.rashost.com的文件的内容如下:
server {
        listen   80;
        server_name  test1.rashost.com;

        location / {
                proxy_pass http://www.baidu.com/;
                proxy_redirect off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}
test2.rashost.com的文件的内容如下:
server {
        listen   80;
        server_name  test2.rashost.com;

        location / {
                proxy_pass http://www.kernel.org/;
                proxy_redirect off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

然后运行命令:
cd /etc/nginx/sites-enabled
ln -sf /etc/nginx/sites-available/test1.rashost.com .ln -sf /etc/nginx/sites-available/test2.rashost.com .
/etc/init.d/nginx restart
这时候在浏览器里面访问test1.rashost.com将会出现www.baidu.com的内容,访问test2.rashost.com将会出现www.kernel.org的内容。

反向代理的高级配置

关于Nginx反向代理的一些高级配置,我们会不断写博客介绍,敬请关注。

博客文章分类:

博客文章标签: