如何在nginx中从$host检查端口号

b1uwtaje  于 12个月前  发布在  Nginx
关注(0)|答案(1)|浏览(205)

我想检查https服务器块中的$host变量中的端口号。如何才能做到这一点?
在端口80的服务器块中。我重定向到端口443的https服务器块。如果这是完整的请求http://localhost:52379/Dika/unityphp/gateway.php。由于端口52379已经被端口转发到端口80,我假设$host变量看起来像这样localhost:52379,request_uri是/Dika/unityphp/gateway.php

server {
    # Configuration for port 80. Unity POB Client
    listen 80;
    server_name localhost;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /code;
    index index.php index.html;

    # Redirect HTTP to HTTPS
    return 307 https://$host$request_uri;
}

server {
    # Configuration for port 443. For https
    listen 443 ssl;
    listen [::]:443 ssl;
    index index.php index.html;
    server_name localhost;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /code;

    include /etc/nginx/certs/self-signed.conf;
    include /etc/nginx/certs/ssl-params.conf;

    #if $host contains port number 52379 or 80 return true

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:52379;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

字符串
我很感激你的帮助谢谢

axzmvihb

axzmvihb1#

传入nginx服务器的请求是由nginx config文件定义的,就像你拥有的那样。

注意如果不匹配块,nginx将返回404状态码,如果nginx重定向到未定义的路由,它将返回502状态码,因为没有网关

每个server block都有它自己的端口,通过使用'listening'属性定义它,每个块都有它自己的代码,无论你想重定向它还是只是传递你在vps上运行的应用程序的本地主机地址。
这里你使用ssl来升级链接到https。ssl https请求的默认端口是443,你可以使用你指定的servername属性来访问它。
当你第一次创建nginx config文件时,它的默认端口是80,你可以手动更改它。
因此,如果您想根据端口执行不同的作业,可以为服务器定义多个server blocks
也可以在config file中定义config rules,如下所示:

map $server_port $port_config {
    default       "default_config";
    80            "port_80_config";
    443           "port_443_config";
}

server {
    listen 80;
    server_name example.com;

    location / {
        # Use the configuration based on the port
        include $port_config;
    }
}

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/ssl_certificate;
    ssl_certificate_key /path/to/ssl_certificate_key;

    location / {
        # Use the configuration based on the port
        include $port_config;
    }
}

# Define configurations for different ports
location @default_config {
    return 404;
}

location @port_80_config {
    # Configuration for port 80
    return 200 "This is port 80 configuration\n";
}

location @port_443_config {
    # Configuration for port 443 (HTTPS)
    return 200 "This is port 443 configuration\n";
}

字符串

相关问题