首先,我们需要安装Nginx。安装方式视操作系统而定,这里不再赘述。
接下来,我们需要在Nginx配置文件中设置反向代理。以Ubuntu系统为例,Nginx的配置文件位于 `/etc/nginx/sites-available/default`,我们可以使用以下命令打开它:
sudo nano /etc/nginx/sites-available/default
在配置文件中,我们需要添加一个 location 条目,指定反向代理的路径和后端服务的地址。假设我们的后端服务地址为 `http://localhost:8080`,反向代理地址为 `/api`,那么配置文件应该如下所示:
server {
listen 80;
listen [::]:80;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com;
location /api {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
try_files $uri $uri/ =404;
}
}
其中,`proxy_pass` 指定后端服务的地址,`proxy_set_header` 则设置请求头,这里设置了 Host 和 X-Real-IP。
配置文件修改完毕后,我们需要重新启动 Nginx:
sudo service nginx restart
这样,我们的反向代理就设置完成了。下面是一个完整的示例,包括后端服务和 Nginx 配置文件。
后端服务代码:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}
Nginx 配置文件:
server {
listen 80;
listen [::]:80;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com;
location /api {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
try_files $uri $uri/ =404;
}
}