Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: return error 403 and display a message

I'd like nginx to return an error 403 if user-agent is MSIE 6 and to display a custom error message. I used this code and everything worked the first minutes. Then it just returned the error without the message! Don't know why... Here's the code (I tried to put ' instead of ", to have plain text without ' or ", still no luck):

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;           
    include /etc/nginx/fastcgi.conf;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    if ($http_user_agent ~ "MSIE 6" ) {
      return 403 "Browser not supported. Please update or change to another one.";
    }
}

EDIT: Forgot to say that it's in the php block because I want to block MSIE 6 only for PHP requests.

like image 490
MultiformeIngegno Avatar asked Dec 25 '12 21:12

MultiformeIngegno


1 Answers

Actually, your configuration should work. You can check it using curl:

# curl -i -H "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1" http://localhost/i.php
HTTP/1.1 403 Forbidden
Server: nginx/1.3.6
Date: Wed, 26 Dec 2012 10:05:34 GMT
Content-Type: application/octet-stream
Content-Length: 62
Connection: keep-alive

Browser not supported. Please update or change to another one.

Access log is also worth checking (by default log_format includes $http_user_agent variable).

By the way, what's in /etc/nginx/fastcgi.conf?

Another thing is that if you want people with real MSIE 6 browsers to see your message, you'd better do something like this:

location ~ \.php$ {
    ...
    if ($http_user_agent ~ "MSIE 6" ) {
        return 403;
    }
    error_page 403 /old_browser.html;
}

and create old_browser.html with your message. Please note that this file should be larger than 512 bytes in order to ensure that MSIE will display it's contents instead of some standart IE 403 message. Tools like http://browsershots.org are perfect for debugging such cases. :)

like image 166
Andrei Belov Avatar answered Sep 29 '22 15:09

Andrei Belov