Files
1Panel/agent/utils/nginx/components/server.go
双向极端andBOX e66f808ed6 Feat/Add custom HTTPS redirect port option for websites (#14491)
* feat(website): add custom HTTPS redirect port option

Allow HTTP-to-HTTPS redirects to omit the local HTTPS port for Cloudflare or other reverse-proxy deployments terminating at 443. Apply the setting to existing websites and update HTTPS settings labels.

(cherry picked from commit 27c1468405)

* feat(website): configure HTTPS redirect port per site

Add a per-site HTTPS redirect port policy next to the HTTP-to-HTTPS option. Sites can inherit the global setting, use the Nginx HTTPS port, or force standard port 443, defaulting existing sites to inheritance.

This supports reverse-proxied sites that need 443 and directly exposed sites that need 8443 on the same host. Global changes now update only inheriting sites, so adjusting one website does not rewrite other sites' redirect rules.

Hide the global custom-port switch when Nginx uses standard port 443.

(cherry picked from commit 301dc15d9d)

* Revert "feat(website): configure HTTPS redirect port per site"

This reverts commit 83d94f6cf9.

The per-site database strategy will be replaced by a config-driven design.

* feat(website): make HTTPS redirect port config-driven

Read the site redirect port from managed nginx rules instead of storing per-site policy in the database. Only update rules matching the old global port, preserve manual configurations, and avoid rewriting sites when the global redirect setting is unchanged.

---------

Co-authored-by: BOX <no@mail.com>
2026-11-26 14:14:28 +08:00

832 lines
21 KiB
Go

package components
import (
"crypto/rand"
"errors"
"fmt"
"slices"
"strconv"
"strings"
)
type Server struct {
Comment string
Listens []*ServerListen
Directives []IDirective
Line int
Cors bool
AllowMethods string
AllowHeaders string
AllowOrigins string
AllowCredentials bool
Preflight bool
}
func (s *Server) GetCodeBlock() string {
return ""
}
func NewServer(directive IDirective) (*Server, error) {
server := &Server{}
if block := directive.GetBlock(); block != nil {
server.Line = directive.GetBlock().GetLine()
server.Comment = block.GetComment()
directives := block.GetDirectives()
for _, dir := range directives {
switch dir.GetName() {
case "listen":
server.Listens = append(server.Listens, NewServerListen(dir.GetParameters(), dir.GetLine()))
case "add_header":
params := dir.GetParameters()
if params[0] == "Access-Control-Allow-Origin" {
server.Cors = true
server.AllowOrigins = params[1]
}
if params[0] == "Access-Control-Allow-Methods" {
server.AllowMethods = params[1]
}
if params[0] == "Access-Control-Allow-Headers" {
server.AllowHeaders = params[1]
}
if params[0] == "Access-Control-Allow-Credentials" && params[1] == "true" {
server.AllowCredentials = true
}
server.Directives = append(server.Directives, dir)
case "if":
params := dir.GetParameters()
if params[0] == "(" && params[1] == "$request_method" && params[2] == `=` && params[3] == `'OPTIONS'` && params[4] == ")" {
server.Preflight = true
}
server.Directives = append(server.Directives, dir)
default:
server.Directives = append(server.Directives, dir)
}
}
return server, nil
}
return nil, errors.New("server directive must have a block")
}
func (s *Server) GetName() string {
return "server"
}
func (s *Server) GetParameters() []string {
return []string{}
}
func (s *Server) GetBlock() IBlock {
return s
}
func (s *Server) GetComment() string {
return s.Comment
}
func (s *Server) GetDirectives() []IDirective {
directives := make([]IDirective, 0)
for _, ls := range s.Listens {
directives = append(directives, ls)
}
directives = append(directives, s.Directives...)
return directives
}
func (s *Server) FindDirectives(directiveName string) []IDirective {
directives := make([]IDirective, 0)
for _, directive := range s.Directives {
if directive.GetName() == directiveName {
directives = append(directives, directive)
}
if directive.GetBlock() != nil {
directives = append(directives, directive.GetBlock().FindDirectives(directiveName)...)
}
}
if directiveName == "listen" {
for _, listen := range s.Listens {
params := []string{listen.Bind}
params = append(params, listen.Parameters...)
if listen.DefaultServer != "" {
params = append(params, DefaultServer)
}
directives = append(directives, &Directive{
Name: "listen",
Parameters: params,
})
}
}
return directives
}
func (s *Server) UpdateDirective(key string, params []string) {
if key == "" || len(params) == 0 {
return
}
if key == "listen" {
defaultServer := false
paramLen := len(params)
if paramLen > 0 && params[paramLen-1] == "default_server" {
params = params[:paramLen-1]
defaultServer = true
}
s.UpdateListen(params[0], defaultServer, params[1:]...)
return
}
directives := s.Directives
index := -1
for i, dir := range directives {
if dir.GetName() == key {
if IsRepeatKey(key) {
oldParams := dir.GetParameters()
if !(len(oldParams) > 0 && oldParams[0] == params[0]) {
continue
}
}
index = i
break
}
}
newDirective := &Directive{
Name: key,
Parameters: params,
}
if index > -1 {
directives[index] = newDirective
} else {
directives = append(directives, newDirective)
}
s.Directives = directives
}
func (s *Server) RemoveDirective(key string, params []string) {
directives := s.Directives
var newDirectives []IDirective
for _, dir := range directives {
if dir.GetName() == key {
if len(params) == 0 {
continue
}
oldParams := dir.GetParameters()
if key == "location" {
if len(params) == len(oldParams) {
exist := true
for i := range params {
if params[i] != oldParams[i] {
exist = false
break
}
}
if exist {
continue
}
}
} else {
if oldParams[0] == params[0] {
continue
}
}
}
newDirectives = append(newDirectives, dir)
}
s.Directives = newDirectives
}
func (s *Server) GetLine() int {
return s.Line
}
func (s *Server) AddListen(bind string, defaultServer bool, params ...string) {
listen := &ServerListen{
Bind: bind,
Parameters: params,
}
if defaultServer {
listen.DefaultServer = DefaultServer
}
s.Listens = append(s.Listens, listen)
}
func isSameArray(arr1, arr2 []string) bool {
set1 := make(map[string]struct{})
for _, v := range arr1 {
set1[v] = struct{}{}
}
for _, v := range arr2 {
if _, exists := set1[v]; !exists {
return false
}
}
return true
}
func (s *Server) UpdateListen(bind string, defaultServer bool, params ...string) {
listen := &ServerListen{
Bind: bind,
Parameters: params,
}
if defaultServer {
listen.DefaultServer = DefaultServer
}
var newListens []*ServerListen
exist := false
for _, li := range s.Listens {
if li.Bind == bind && isSameArray(li.Parameters, params) {
exist = true
newListens = append(newListens, listen)
} else {
newListens = append(newListens, li)
}
}
if !exist {
newListens = append(newListens, listen)
}
s.Listens = newListens
}
func (s *Server) DeleteListen(bind string) {
var newListens []*ServerListen
for _, li := range s.Listens {
if li.Bind != bind {
newListens = append(newListens, li)
}
}
s.Listens = newListens
}
func (s *Server) RemoveListen(bind string, params ...string) {
var newListens []*ServerListen
for _, li := range s.Listens {
if li.Bind == bind && isSameArray(li.Parameters, params) {
continue
}
newListens = append(newListens, li)
}
s.Listens = newListens
}
func (s *Server) DeleteServerName(name string) {
var names []string
dirs := s.FindDirectives("server_name")
params := dirs[0].GetParameters()
for _, param := range params {
if param != name {
names = append(names, param)
}
}
s.UpdateServerName(names)
}
func (s *Server) AddServerName(name string) {
dirs := s.FindDirectives("server_name")
params := dirs[0].GetParameters()
params = append(params, name)
s.UpdateServerName(params)
}
func (s *Server) UpdateServerName(names []string) {
s.UpdateDirective("server_name", names)
}
func (s *Server) UpdateRoot(path string) {
s.UpdateDirective("root", []string{path})
}
const StopPageRoot = "/usr/share/nginx/html/stop"
const stopPageComment = "# 1Panel managed stop page"
const stopPagePattern = `"^/(?![.]well-known/acme-challenge(?:/|$))"`
// EnableStopPage reports whether the configuration needs to be written.
func (s *Server) EnableStopPage() bool {
httpsOnly := slices.ContainsFunc(s.Directives, isHTTP2HTTPSRedirect)
if s.HasStopPage() && stopPageRewrite(s.Directives[0]) != nil &&
(s.Directives[0].GetName() == "if") == httpsOnly {
return false
}
s.DisableStopPage()
// Includes resolve inside OpenResty. Give each activation its own exact
// location instead of claiming a fixed URI from the site's namespace.
uri := "/.1panel-stop/" + rand.Text() + "/index.html"
var rewrite IDirective = &Directive{
Name: "rewrite", Comment: stopPageComment,
Parameters: []string{stopPagePattern, uri, "last"},
}
if httpsOnly {
// Let HTTP requests follow the site's existing redirect, including its port.
rewrite = &Directive{Name: "if", Parameters: []string{"(", "$scheme", "=", "https", ")"},
Block: &Block{Directives: []IDirective{rewrite}}}
}
location := &Directive{
Name: "location", Parameters: []string{"=", uri},
Block: &Block{Directives: []IDirective{
&Directive{Name: "root", Parameters: []string{StopPageRoot}},
&Directive{Name: "try_files", Parameters: []string{"/index.html", "=404"}},
}},
}
s.Directives = append([]IDirective{rewrite, location}, s.Directives...)
return true
}
func stopPageRewrite(dir IDirective) IDirective {
if dir.GetName() == "if" && dir.GetBlock() != nil {
children := dir.GetBlock().GetDirectives()
if len(children) != 1 || strings.Join(dir.GetParameters(), "") != "($scheme=https)" {
return nil
}
dir = children[0]
}
if dir.GetName() == "rewrite" && dir.GetComment() == stopPageComment && len(dir.GetParameters()) == 3 {
return dir
}
return nil
}
func (s *Server) DisableStopPage() {
for _, dir := range s.Directives {
if rewrite := stopPageRewrite(dir); rewrite != nil {
uri := rewrite.GetParameters()[1]
s.Directives = slices.DeleteFunc(s.Directives, func(d IDirective) bool {
return d == dir || d.GetName() == "location" && slices.Equal(d.GetParameters(), []string{"=", uri})
})
return
}
}
}
func (s *Server) HasStopPage() bool {
for _, dir := range s.Directives {
rewrite := stopPageRewrite(dir)
if rewrite == nil {
continue
}
params := rewrite.GetParameters()
if params[0] != stopPagePattern || params[2] != "last" {
return false
}
for _, location := range s.Directives {
if location.GetName() != "location" || !slices.Equal(location.GetParameters(), []string{"=", params[1]}) || location.GetBlock() == nil {
continue
}
children := location.GetBlock().GetDirectives()
return len(children) == 2 && children[0].GetName() == "root" &&
slices.Equal(children[0].GetParameters(), []string{StopPageRoot}) &&
children[1].GetName() == "try_files" && slices.Equal(children[1].GetParameters(), []string{"/index.html", "=404"})
}
}
return false
}
func (s *Server) UpdateRootProxyForAi(proxy []string) {
newDir := Directive{
Name: "location",
Parameters: []string{"/"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(
&Directive{
Name: "proxy_buffering",
Parameters: []string{
"off",
},
},
&Directive{
Name: "proxy_cache",
Parameters: []string{
"off",
},
},
&Directive{
Name: "proxy_http_version",
Parameters: []string{
"1.1",
},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{
"Connection", "''",
},
},
&Directive{
Name: "chunked_transfer_encoding",
Parameters: []string{
"off",
},
},
&Directive{
Name: "proxy_pass",
Parameters: proxy,
},
)
newDir.Block = block
s.UpdateDirectiveBySecondKey("location", "/", newDir)
}
func (s *Server) UpdateRootLocation() {
newDir := Directive{
Name: "location",
Parameters: []string{"/"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(&Directive{
Name: "root",
Parameters: []string{"index.html"},
})
newDir.Block = block
}
func (s *Server) UpdateRootProxy(proxy []string) {
httpsProxy := len(proxy) > 0 && strings.HasPrefix(strings.ToLower(strings.TrimSpace(proxy[0])), "https://")
newDir := Directive{
Name: "location",
Parameters: []string{"/"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(
&Directive{
Name: "proxy_set_header",
Parameters: []string{"Host", "$host"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"X-Forwarded-For", "$proxy_add_x_forwarded_for"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"X-Forwarded-Host", "$server_name"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"X-Real-IP", "$remote_addr"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"X-Forwarded-Proto", "$scheme"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"Connection", "upgrade"},
},
&Directive{
Name: "proxy_set_header",
Parameters: []string{"Upgrade", "$http_upgrade"},
},
&Directive{
Name: "proxy_http_version",
Parameters: []string{"1.1"},
},
&Directive{
Name: "proxy_ssl_server_name",
Parameters: []string{map[bool]string{true: "on", false: "off"}[httpsProxy]},
},
&Directive{
Name: "proxy_ssl_name",
Parameters: []string{"$proxy_host"},
},
&Directive{
Name: "proxy_pass",
Parameters: proxy,
},
)
newDir.Block = block
s.UpdateDirectiveBySecondKey("location", "/", newDir)
}
func NewPHPProxyDirective(proxy []string, localPath string) *Directive {
newDir := &Directive{
Name: "location",
Parameters: []string{"~", "[^/]\\.php(/|$)"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(
&Directive{
Name: "fastcgi_pass",
Parameters: proxy,
},
&Directive{
Name: "include",
Parameters: []string{"fastcgi-php.conf"},
},
&Directive{
Name: "include",
Parameters: []string{"fastcgi_params"},
},
)
if localPath == "" {
block.AppendDirectives(&Directive{
Name: "set",
Parameters: []string{"$real_script_name", "$fastcgi_script_name"},
})
ifDir := &Directive{
Name: "if",
Parameters: []string{"($fastcgi_script_name ~ \"^(.+?\\.php)(/.+)$\")"},
}
ifDir.Block = &Block{
Directives: []IDirective{
&Directive{
Name: "set",
Parameters: []string{"$real_script_name", "$1"},
},
&Directive{
Name: "set",
Parameters: []string{"$path_info", "$2"},
},
},
}
block.AppendDirectives(
ifDir,
&Directive{
Name: "fastcgi_param",
Parameters: []string{"SCRIPT_FILENAME", "$document_root$real_script_name"},
},
&Directive{
Name: "fastcgi_param",
Parameters: []string{"SCRIPT_NAME", "$real_script_name"},
},
&Directive{
Name: "fastcgi_param",
Parameters: []string{"PATH_INFO", "$path_info"},
})
} else {
block.AppendDirectives(&Directive{
Name: "fastcgi_param",
Parameters: []string{"SCRIPT_FILENAME", localPath},
})
}
newDir.Block = block
return newDir
}
func (s *Server) UpdatePHPProxy(proxy []string, localPath string) {
newDir := NewPHPProxyDirective(proxy, localPath)
s.UpdateDirectiveBySecondKey("location", "~ [^/]\\.php(/|$)", *newDir)
}
func (s *Server) UpdateDirectiveBySecondKey(name string, key string, directive Directive) {
directives := s.Directives
index := -1
for i, dir := range directives {
if dir.GetName() == name && strings.Join(dir.GetParameters(), " ") == key {
index = i
break
}
}
if index > -1 {
directives[index] = &directive
} else {
directives = append(directives, &directive)
}
s.Directives = directives
}
func (s *Server) RemoveListenByBind(bind string) {
var listens []*ServerListen
for _, listen := range s.Listens {
if listen.Bind != bind {
listens = append(listens, listen)
}
}
s.Listens = listens
}
func (s *Server) AddHTTP2HTTPS(httpsPort int) {
newDir := Directive{
Name: "if",
Parameters: []string{"($scheme = http)"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(&Directive{
Name: "return",
Parameters: []string{"301", HTTPSRedirectTarget(httpsPort)},
})
newDir.Block = block
directives := make([]IDirective, 0, len(s.Directives)+1)
insertAt := -1
for _, dir := range s.Directives {
params := dir.GetParameters()
isHTTPRedirect := isHTTP2HTTPSRedirect(dir)
isRedirectInclude := dir.GetName() == "include" && len(params) > 0 &&
strings.HasSuffix(strings.Trim(params[0], "\"'"), "/redirect/*.conf")
if insertAt == -1 && (isHTTPRedirect || isRedirectInclude) {
insertAt = len(directives)
}
if !isHTTPRedirect {
directives = append(directives, dir)
}
}
if insertAt == -1 {
insertAt = len(directives)
}
directives = append(directives, nil)
copy(directives[insertAt+1:], directives[insertAt:])
directives[insertAt] = &newDir
s.Directives = directives
}
func isHTTP2HTTPSRedirect(dir IDirective) bool {
_, ok := http2HTTPSRedirectTarget(dir)
return ok
}
func http2HTTPSRedirectTarget(dir IDirective) (string, bool) {
condition := strings.Join(dir.GetParameters(), " ")
normalizedCondition := strings.Join(strings.Fields(condition), "")
if dir.GetName() != "if" || normalizedCondition != "($scheme=http)" || dir.GetBlock() == nil {
return "", false
}
var returnDirective IDirective
for _, child := range dir.GetBlock().GetDirectives() {
if _, ok := child.(*Comment); ok {
continue
}
if returnDirective != nil || child.GetName() != "return" || child.GetBlock() != nil {
return "", false
}
returnDirective = child
}
if returnDirective == nil {
return "", false
}
params := returnDirective.GetParameters()
if len(params) != 2 || params[0] != "301" {
return "", false
}
if _, ok := ParseHTTPToHTTPSRedirectPort(params[1]); !ok {
return "", false
}
return params[1], true
}
// HTTPSRedirectTarget builds the redirect target used by HTTP-to-HTTPS rules.
func HTTPSRedirectTarget(httpsPort int) string {
if httpsPort == 443 {
return "https://$host$request_uri"
}
return fmt.Sprintf("https://$host:%d$request_uri", httpsPort)
}
// ParseHTTPToHTTPSRedirectPort extracts the port from a managed redirect target.
func ParseHTTPToHTTPSRedirectPort(target string) (int, bool) {
if target == "https://$host$request_uri" {
return 443, true
}
port, ok := strings.CutPrefix(target, "https://$host:")
if !ok || !strings.HasSuffix(port, "$request_uri") {
return 0, false
}
value, err := strconv.ParseUint(strings.TrimSuffix(port, "$request_uri"), 10, 16)
if err != nil || value == 0 {
return 0, false
}
return int(value), true
}
// IsHTTPToHTTPSRedirectTarget reports whether target is a managed HTTP-to-HTTPS redirect.
func IsHTTPToHTTPSRedirectTarget(target string) bool {
_, ok := ParseHTTPToHTTPSRedirectPort(target)
return ok
}
type HTTPToHTTPSRedirectState struct {
Managed bool
Port int
Present bool
HasUnmanaged bool
}
// HTTPToHTTPSRedirectState returns the effective managed redirect state of a server.
func (s *Server) HTTPToHTTPSRedirectState() HTTPToHTTPSRedirectState {
ports := make(map[int]struct{})
state := HTTPToHTTPSRedirectState{}
for _, dir := range s.Directives {
switch dir.GetName() {
case "if":
condition := strings.Join(dir.GetParameters(), " ")
if strings.Join(strings.Fields(condition), "") != "($scheme=http)" {
continue
}
state.Present = true
target, ok := http2HTTPSRedirectTarget(dir)
if !ok {
state.HasUnmanaged = true
continue
}
port, _ := ParseHTTPToHTTPSRedirectPort(target)
ports[port] = struct{}{}
case "error_page":
params := dir.GetParameters()
if len(params) == 0 || params[0] != "497" {
continue
}
state.Present = true
if len(params) < 2 {
state.HasUnmanaged = true
continue
}
port, ok := ParseHTTPToHTTPSRedirectPort(params[1])
if !ok {
state.HasUnmanaged = true
continue
}
ports[port] = struct{}{}
}
}
if len(ports) == 1 {
for port := range ports {
state.Port = port
}
}
if !state.HasUnmanaged && len(ports) == 1 {
state.Managed = true
}
return state
}
// SetHTTPToHTTPSRedirectPort updates redirects that are already recognized as managed.
func (s *Server) SetHTTPToHTTPSRedirectPort(port int) {
if !s.HTTPToHTTPSRedirectState().Managed {
return
}
target := HTTPSRedirectTarget(port)
for _, dir := range s.Directives {
switch dir.GetName() {
case "if":
if _, ok := http2HTTPSRedirectTarget(dir); ok {
dir.GetBlock().UpdateDirective("return", []string{"301", target})
}
case "error_page":
params := dir.GetParameters()
if len(params) >= 2 && params[0] == "497" {
if _, ok := ParseHTTPToHTTPSRedirectPort(params[1]); ok {
directive, ok := dir.(*Directive)
if ok {
directive.Parameters[1] = target
}
}
}
}
}
}
func (s *Server) UpdateAllowIPs(ips []string) {
index := -1
for i, directive := range s.Directives {
if directive.GetName() == "location" && directive.GetParameters()[0] == "/" {
index = i
break
}
}
ipDirectives := make([]IDirective, 0)
for _, ip := range ips {
ipDirectives = append(ipDirectives, &Directive{
Name: "allow",
Parameters: []string{ip},
})
}
ipDirectives = append(ipDirectives, &Directive{
Name: "deny",
Parameters: []string{"all"},
})
if index != -1 {
newDirectives := append(ipDirectives, s.Directives[index:]...)
s.Directives = append(s.Directives[:index], newDirectives...)
} else {
s.Directives = append(s.Directives, ipDirectives...)
}
}
func (s *Server) AddCorsOption() {
newDir := &Directive{
Name: "if",
Parameters: []string{"(", "$request_method", "=", "'OPTIONS'", ")"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(&Directive{
Name: "return",
Parameters: []string{"204"},
})
newDir.Block = block
directives := s.GetDirectives()
newDirectives := make([]IDirective, 0)
for _, dir := range directives {
if dir.GetName() != "listen" {
newDirectives = append(newDirectives, dir)
}
}
newDirectives = append(newDirectives, newDir)
s.Directives = newDirectives
}