如何将所有请求redirect到特定的域名?

我在App Engine上为我的网站设置了SSL和自定义域名。

它工作得很好:我可以去https://www.mywebsite.com和页面加载。

但是我想做一下改变。

如果我去mywebsite.com,我会立即redirect到https://www.mywebsite.com 。

我怎样才能做到这一点 ?

如果你正在使用expressjs,那么下面的代码将做到这一点。

  app.get('*', function (req, res, next) { var checkHost = req.get('host').substring(0, 4); var condition = req.get('x-forwarded-proto') !== "https" || checkHost !== 'www.' || ( req.get('host').indexOf('www.') < 0); if (condition) { res.set('x-forwarded-proto', 'https'); if (checkHost === 'www.' && ( req.get('host').indexOf('www.') >= 0)) { res.redirect('https://' + req.get('host') + req.url); } else { res.redirect('https://www.' + req.get('host') + req.url); } } else { next(); } }); 

您可以在开始添加路线之前进行此操作。 它会检查每个请求的协议,并redirect到https版本,如果它通过http进入

 app.use(function(req, res, next) { if (req.protocol === 'http') { var host = req.host.replace('www.', ''); return res.redirect('https://www.' + host + req.originalUrl); } next(); }); 

请注意,如果nginx / apache正在处理https的东西,并转发到非https节点服务器,这是不够的。 你需要看看你的条件,而不是req.protocol (像req.protocol东西)

您需要在服务器的根目录下创build.htaccess文件以进行redirect。

.htaccess文件

 <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} folder RewriteRule ^(.*)$ https://www.urserver.com/folder/$1 [R,L] </IfModule> 

使用上限,你可以redirect到你的域名

除了您的www.mywebsite.com ,您还可以将裸露的域名 mywebsite.com映射到您的GAE应用程序。 基本上通过重复的步骤为您的应用程序添加一个自定义域,并在第4步select裸域(强调我的):

继续添加新的自定义域表单的下一步,然后select要指向您的App Engine应用程序的自定义域:

  • 指定您想要映射的域和子域。

    注意:裸域和www子域预填充在表单中。

    • 一个裸体域(如example.com )映射到http://example.com
    • 子域名(如www )映射到http://www.example.com
  • 点击Submit mappings来创build所需的映射。

优点:

  • 简单
  • 适用于标准和灵活的env应用程序,不pipe应用程序的语言如何
  • 也适用于静态内容,与基于应用程序代码更改的解决scheme不同

缺点:

  • 至less对于标准的env应用程序, https请求可能有2个redirect:

    • 第一个是301redirect到http://www.mywebsite.com
    • 第二个是302redirect到https://www.mywebsite.com