How to use ssh to proxy local services to external access and maintain SSH session connectivity
1. External server nginx configuration
server {
listen localhost:80;
server_name _;
root /usr/share/nginx/html;
# 重要:将请求转发到本地服务
location / {
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://127.0.0.1:10412;
proxy_set_header Host $host:80;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Via "nginx";
}
}
2. Authorization authentication
- Run the following command on the extranet server to generate the public key:
ssh-keygen -o
- Copy the public key to the intranet server and add it to
~/.ssh/authorized_keys
3. SSH connection to the target intranet server
- Start the service locally and listen on port 8088
- Forward port 10412 accessed from the external network to local port 8088
nohup ssh -N -v -R 10412:127.0.0.1:8088 root@{
外部服务器的外网IP} 2>&1 &
4. Keep the session
- In keep the SSH session, add the following command to keep the connection
- ServerAliveInterval is the time for the specified server to send a packet to keep the connection (unit: second)
- ServerAliveCountMax is the specified maximum number of attempts to maintain a connection with the server
nohup ssh -N -v -o ServerAliveInterval=10 -o ServerAliveCountMax=1000 -R 10412:127.0.0.1:8088 root@{
外部服务器的外网IP} 2>&1 &