Skip to content

Instantly share code, notes, and snippets.

@fujimura
Last active April 18, 2022 07:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujimura/3168838 to your computer and use it in GitHub Desktop.
Save fujimura/3168838 to your computer and use it in GitHub Desktop.
Nginx configuration generator for port-forwarding with reverse proxy

Nginx configuration generator for port-forwarding with reverse proxy

How to use

Write your config like conf.example and

$ cat your_config | ruby run.rb

How to forward request via ssh(port forwarding)

Synopsis

$ ssh -g -N user@subdomain.somedomain.com -R '*:4001:localhost:3000'

Option details

  • -g

Means 'Allows remote hosts to connect to local forwarded ports'

  • -N

Means 'Do not execute a remote command. This is useful for just forwarding ports (protocol version 2 only)'

  • -R '*:4001:localhost:3000'

Means 'Forward request to remote:4001 to localhost:3000'

Reverse proxy server tips

  • Configure GatewayPorts in sshd_config to yes

License

MIT License

# <%= @name %>
server {
server_name <%= @host %>;
location / {
proxy_pass http://127.0.0.1:<%= @port %>;
proxy_set_header X-Forwarded-Host $host;
}
}
| 7001 | a.example.com | Bill Gates |
| 7002 | b.example.com | Steve Ballmer |
| 7003 | c.example.com | xxx |
| 7004 | d.example.com | xxx |
| 7005 | e.example.com | xxx |
require 'erb'
class Conf
BLANK_NAME = 'xxx'
def initialize(line)
process line
end
# Read line and store values
# Sample data:
# | 4001 | fujimura.somewhere.com | 藤村 |
#
def process line
_, @port, @host, @name, _ = line.split("|").map(&:strip)
unless @port && @host && @name
raise StandardError.new %|Invalid line :"#{line}"|
end
end
# Return configuration block of reverse proxy seting for nginx
#
def to_conf
return nil if @name == BLANK_NAME
return nil if [@name, @host, @port].any?(&:nil?)
ERB.new(File.read('./conf.erb')).result(binding)
end
end
require './conf'
STDIN.read.split("\n").each do |line|
conf = Conf.new(line).to_conf
puts conf unless conf.nil?
end
  • Support configuration file format other than textile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment