将example.com:3000重定向到example.com

时间:2018-01-26 14:17:59

标签: node.js redirect nginx

重定向(301)https://example.com:3000https://example.com,而3000端口只能通过IP:3000访问,而不能通过example.com:3000

  • 在端口3000上使用Express.js应用程序。
  • 使用nginx通过example.com代理localhost:3000。
  • 现在https://example.com:3000无法访问(在chrome中: ERR_CONNECTION_CLOSED),但可以访问IP:3000。
  • 问题是 - 搜索引擎几乎全部索引 https://example.com:3000页面和这些页面无法访问。

由于nodejs已经占用了3000端口,在nginx中我无法写入:

server {
    listen 3000;
    server_name example.com;
    return 301 https://example.com$request_uri;
}

nginx conf:

upstream nodejs {
    ip_hash;
    server localhost:3000;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {

    listen 443 ssl  default_server;
    server_name example.com;

    listen [::]:443 ssl  default_server;

    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    include /etc/nginx/snippets/letsencrypt-acme-challenge.conf;


    location = /robots.txt {
        root /root;
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~* \.(?:css|js)$ {
        root /root;

        expires 9d;

        add_header Cache-Control "public, max-age=7200";
        add_header X-Content-Type-Options nosniff;
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_header X-Permitted-Cross-Domain-Policies none;
        # Optional: Don't log access to assets
        access_log off;
    }

    location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|flv|swf)$
    {
        root /root;    
        expires 365d;
        access_log off;
    }

    # @nodejs
    location / {

        add_header Cache-Control "private";
        add_header Vary "Cookie, User-Agent";

        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_cache_bypass $http_upgrade; 

        include /etc/nginx/proxy_params;

        proxy_pass http://nodejs;
    }
}

https://example.com:3000 => https://example.com 并限制对3000端口的外部访问(仅保留localhost:3000)?

1 个答案:

答案 0 :(得分:0)

再添加一个服务器块,如下所示:

server {
    listen EXTERNAL_IP:3000 ;
    server_name example.com;

    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;
    include /etc/nginx/snippets/letsencrypt-acme-challenge.conf;    

    return 301 https://$server_name$request_uri;
}

请注意,该应用程序应该只收听127.0.0.1:3000,否则您可能会遇到“已在使用的地址”。

在这种情况下,将使用nginx建立所有传入连接,nginx会根据您的规则重定向用户。

如果要限制对端口3000的访问,可以使用任何防火墙。 iptables示例:

iptables -I INPUT -p tcp -i eth1 --dport 3000 -j DROP

但这也会关闭https://example.com:3000的访问权限。