Nginx rewrite URL examples with and without redirect address

本文介绍如何使用Nginx配置URL重写及转发功能。通过具体示例展示了如何进行页面重定向、保持域名的内部URL重写以及如何将请求代理到后台服务器如Tomcat等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址: http://www.claudiokuenzler.com/blog/436/nginx-rewrite-url-examples-with-without-redirect-address#.VY9nfJeqqko

Nginx can handle the rewrite parameter differently, depending on the destination syntax. 

Here are some examples how to define redirects and URL rewrites in nginx. 

server { 
    server_name www.example.com; 
    root /var/www/www.example.com; 

    location / { 
        rewrite ^/$ http://websrv1.example.com/mypage redirect; 
    } 

This will result in forwarding the browser to http://websrv1.example.com/mypage. The redirect address will be shown in the address bar.

Let's try this without a redirect or permanent option but with break or last: 

server { 
    server_name www.example.com; 
    root /var/www/www.example.com; 

    location / { 
        rewrite ^/$ http://websrv1.example.com/mypage last; 
    } 
}

Although the rewrite option is now set to last, the browser will still follow the URL and changes the URL in the address bar. 
The reason for this is the http:// which is interpreted as external redirect.

So if you want to keep your domain and simply want to rewrite the URL (like in Apache with mod_rewrite), you must use a relative path:

server { 
    server_name www.example.com; 
    root /var/www/www.example.com; 

    location / { 
        rewrite ^/$ /mypage last; 
    } 
}

This will load the website for www.example.com from the subfolder /mypage within the document root (/var/www/www.example.com). 

But what if the destination website is loaded from somewhere else, for example from a Tomcat server in the background? 
The following configuration covers this:

upstream tomcat { 
    server 127.0.0.1:8080; 


server { 
    server_name www.example.com; 
    root /var/www/www.example.com; 

    location / { 
        include proxy-settings.conf; 
        proxy_pass http://tomcat; 
        rewrite ^/$ /mypage last; 
    } 
}

First everything (location /) is passed to tomcat (the defined upstream server). Then the redirect for the root path (/) is happening and is relative to the path. 

This results in keeping the browser's address URL at www.example.com but loads the website from 127.0.0.1:8080/mypage. 


贴上这边地址,刚好可以使用搞明白使用 nginx 实现 隐式URL 转发功能,good。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值