案例一:打开浏览器,输入地址 localhost,跳转到百度
在 nginx 配置文件中编写 server 块:
server {listen 80;server_name localhost;location / {proxy_pass https://www.baidu.com;}}
表示,监听 localhost 的 80 端口,若该端口有请求过来,则将请求转到 [https://www.baidu.com](https://www.baidu.com)。
此时,若在浏览器地址栏输入 localhost,则会跳转到百度搜索。
关于 hosts 文件的知识:
hosts文件在C:\Windows\System32\drivers\etc路径下- 在浏览器地址栏中输入一个域名后,例如 http://www.123.com,浏览器会先到本地电脑的 hosts 文件中查找是否有该域名对应的 ip 地址,若无,则会去 DNS 服务器上查找。
PS:这里的 localhost 可以换成其他的域名,若是其他的域名,需要在 hosts 文件中设定映射规则。
比如说,我现在想要实现,在浏览器地址栏中输入 www.123.com,就跳转到 www.baidu.com。我可以通过这样的方式来实现:
有一台 linux 服务器,该服务器的 ip 为 192.168.1.12。首先我在本地电脑的 hosts 文件中设定如下映射规则:
然后在 linux 机的 nginx 配置文件中,定义如下 server 块:
server {listen 80;server_name 192.168.1.12;location / {proxy_pass https://www.baidu.com;}}
案例二:使用 nginx,根据访问的路径跳转到不同端口的服务中
例如,通过下面的代码,可以实现在浏览器访问 localhost:9002/que 时,会跳转到京东首页;访问 localhost:9002/abc 时,会跳转到 bing 首页,
server {listen 9002;server_name localhost;location ~ /que {proxy_pass https://www.jd.com;}location ~ /abc {proxy_pass https://www.bing.com;}}
在代码中,~ 表示使用正则匹配,当在浏览器输入的路径中,出现 localhost:9002/que 时,会自动跳转到京东首页。
