Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have a problem where Nginx redirects me to the wrong url if there is no trailing / provided.

I have haproxy setup to delegate the requests between multiple servers.

curl output:

➜  ~  curl -i www.ordify.com/register
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.19
Date: Tue, 14 Aug 2012 08:10:39 GMT
Content-Type: text/html
Content-Length: 185
Location: http://www.ordify.com:4000/register/
Connection: close

<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>

Nginx config:

server {
    listen *:4000;
    server_name ordify.com;
    access_log  /var/log/nginx/website-com.log;
    rewrite_log on;
    error_page 405 = $uri;

    location / {
      root   /home/website/en/;
      index  index.html index.htm;
    if ($host != 'www.ordify.com' ) {
        rewrite  ^/(.*)$  http://www.ordify.com/$1  permanent;
    rewrite /registrieren/ http://www.ordify.com/register/ permanent;
    rewrite /presse/ http://www.ordify.com/press/ permanent;


I have already tried using http://wiki.nginx.org/HttpCoreModule#server_name_in_redirect without success.

share|improve this question

1 Answer 1

if ($host != 'www.ordify.com' ) {
    rewrite  ^/(.*)$  http://www.ordify.com/$1  permanent;

This is a ineffective way. See: http://nginx.org/en/docs/http/converting_rewrite_rules.html

The right way is to define a separate server to catch all other domains. Server names may be defined using regular expressions. Try this:

server {
    listen      *:4000;
    server_name www.ordify.com;

server {
    listen      *:4000;
    server_name ~^(?!www)\.ordify\.com$;
    return      301 http://www.ordify.com$request_uri;

?!www - negative lookahead, means that match something not followed by www.

share|improve this answer
Does not answer question from OP about trailing slash rewrite. –  pkhamre Aug 14 '12 at 10:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.