301 redirect in Passenger (Ruby on Rails) from roo

2019-08-30 04:57发布

问题:

How can you create a permanent redirect (301) in Passenger? There are posts elsewhere on how to perform the redirect in Rails, but it seems better to do the redirect at the server level rather than at the Rails level.

Any clues?

Thanks!

回答1:

Server-level redirects are done with the HTTP server, not the Application server. Here's some examples:

Apache

<VirtualHost xxx.xxx.xxx.xxx:80>
    ServerAlias example.com
    Redirect Permanent / http://www.example.com
</VirtualHost>

Nginx

server {
  server_name example.com;
  rewrite ^/(.*) http://www.example.com/$1 permanent;
}

Lighttpd

$HTTP["host"] =~ "^example\.com$" {
  url.redirect = ( "^/(.*)" => "http://www.example.com/$1" )
}

While it's technically possible to achieve this later in the stack, like with a Rack app, it makes the most sense to do this as early as possible to save your server cpu cycles. Sometimes you have to do this later, for instance with a host like Heroku that won't let you change your HTTP settings, but if you have the option to do it here that's what I recommend.



回答2:

Are you sure you want it at the Passenger level and not at the Nginx/Apache level... i.e., why have the redirect even get that far down the stack.

Depending on what server you are using, there are resources on the net that tell you how do accomplish this.