[Nginx] common traps and errors: nginx traps

Source: Internet
Author: User
Tags sendfile drupal

[Nginx] common traps and errors: nginx traps

Many people may encounter a trap. The following lists the problems we often see and explains how to solve them. The # nginx IRC channel on Freenode is frequently discussed.

1. Permissions

Never use 777 permission to view directory permissions

namei -om /path/to/check
2. root settings

BAD:

server {    server_name www.example.com;    location / {        root /var/www/nginx-default/;        # [...]      }    location /foo {        root /var/www/nginx-default/;        # [...]    }    location /bar {        root /var/www/nginx-default/;        # [...]    }}

GOOD:

server {    server_name www.example.com;    root /var/www/nginx-default/;    location / {        # [...]    }    location /foo {        # [...]    }    location /bar {        # [...]    }}
3. Index settings

BAD:

http {    index index.php index.htm index.html;    server {        server_name www.example.com;        location / {            index index.php index.htm index.html;            # [...]        }    }    server {        server_name example.com;        location / {            index index.php index.htm index.html;            # [...]        }        location /foo {            index index.php;            # [...]        }    }}

GOOD:

http {    index index.php index.htm index.html;    server {        server_name www.example.com;        location / {            # [...]        }    }    server {        server_name example.com;        location / {            # [...]        }        location /foo {            # [...]        }    }}
4. Using If

If Is Evil.

5. Server Name (If)

BAD:

server {    server_name example.com *.example.com;        if ($host ~* ^www\.(.+)) {            set $raw_domain $1;            rewrite ^/(.*)$ $raw_domain/$1 permanent;        }        # [...]    }}

Check the Host Header every time. This is inefficient. You should avoid this. We recommend that you use the following

GOOD:

server {    server_name www.example.com;    return 301 $scheme://example.com$request_uri;}server {    server_name example.com;    # [...]}

This method is easy to read, reduces nginx processing requirements, and avoids hard encoding (http or https)

6. Check (If) File Exists

If is used to determine whether it is terrible, you should use try_files

BAD:

server {    root /var/www/example.com;    location / {        if (!-f $request_filename) {            break;        }    }}

GOOD:

server {    root /var/www/example.com;    location / {        try_files $uri $uri/ /index.html;    }}

Try_files means you test a queue $ uri =>$ uri/=> index.html. This method is simple and can avoid

7. Web Apps Controller

Drupal, Joomla, etc. to work, just use this:

try_files $uri $uri/ /index.php?q=$uri&$args;

Note-the parameter names are different based on the package you're using. For example:

  • "Q" is the parameter used by Drupal, Joomla, WordPress
  • "Page" is used by CMS Made Simple

Some software does not need query string, and can read REQUEST_URI (for example, WordPress ):

try_files $uri $uri/ /index.php;

If you do not care whether the directory exists, you can remove $ uri/

8. Passing Uncontrolled Requests to PHP

We recommend that you use nginx in many PHP websites. php (to the PHP interpretet) ends with the uri, which has a serious security problem for most PHP programs because it may allow execution of any third-party code

The problem section usually looks like this:

location ~* \.php$ {    fastcgi_pass backend;    # [...]}

Here, every request ending in. php will be passed to the FastCGI backend. the issue with this is that the default PHP configuration tries to guess which file you want to execute if the full path does not lead to an actual file on the filesystem.

For instance, if a request is made/Forum/avatar/1232.jpg/ file. phpWhich does not exist but if/Forum/avatar/1232.jpgDoes, the PHP interpreter will process/Forum/avatar/1232.jpgInstead. If this contains embedded PHP code, this code will be executed accordingly.

Options for avoiding this are:

  • Set cgi. fix_pathinfo = 0 in php. ini. This causes the PHP interpreter to only try the literal path given and to stop processing if the file is not found.
  • Ensure that NGINX only passes specific PHP files for execution:
location ~* (file_a|file_b|file_c)\.php$ {    fastcgi_pass backend;    # [...]}
  • Disable any PHP code execution in the upload directory.
location /uploaddir {    location ~ \.php$ {return 403;}    # [...]}
  • Use the try_files command to filter
location ~* \.php$ {    try_files $uri =404;    fastcgi_pass backend;    # [...]}
  • Filter by nested position
location ~* \.php$ {    location ~ \..*/.*\.php$ {return 404;}    fastcgi_pass backend;    # [...]}
9. FastCGI Path in Script Filename

Use the variables in include fastcgi_params whenever possible, regardless of the language.

GOOD:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

BAD:

fastcgi_param  SCRIPT_FILENAME    /var/www/yoursite.com/$fastcgi_script_name;
10. Taxing Rewrites

We should try to keep them clean. It is very simple. No redundant code is added.

BAD:

rewrite ^/(.*)$ http://example.com/$1 permanent;

GOOD:

rewrite ^ http://example.com$request_uri? permanent;

BETTER:

return 301 http://example.com$request_uri;

By using the built-in variable $ REQUEST_URI, we can effectively avoid any capture or matching.

11. Rewrite Missing http://

Unless you tell NGINX that they are not overwritten. Rewriting is absolutely simple. Add a scheme

BAD:

rewrite ^ example.com permanent;

GOOD:

rewrite ^ http://example.com permanent;

Addhttp://To rewrite rules, simple and efficient

12. Proxy Everything

BAD:

server {    server_name _;    root /var/www/site;    location / {        include fastcgi_params;        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;        fastcgi_pass unix:/tmp/phpcgi.socket;    }}

Yucky. In this instance, you pass EVERYTHING to PHP. Why? Apache might do this, you don't need. let me put it this way... the try_files directive exists for an amazing reason. it tries files in a specific order. this means that NGINX can first try to server the static content. if it can't, then it moves on. this means PHP doesn' t get involved at all. MUCH faster. especially if you're serving a 1 MB image over PHP a few thousand times versus serving it directly. let's take a look at how to do that.

GOOD:

server {    server_name _;    root /var/www/site;    location / {        try_files $uri $uri/ @proxy;    }    location @proxy {        include fastcgi_params;        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;        fastcgi_pass unix:/tmp/phpcgi.socket;    }}

Also GOOD:

server {    server_name _;    root /var/www/site;    location / {        try_files $uri $uri/ /index.php;    }    location ~ \.php$ {        include fastcgi_params;        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;        fastcgi_pass unix:/tmp/phpcgi.socket;    }}

It's easy, right? You see if the requested URI exists and can be served by NGINX. if not, is it a directory that can be served. if not, then you pass it to your proxy. only when NGINX can't serve that requested URI directly does your proxy overhead get involved.

Now .. consider how much of your requests are static content, such as images, css, javascript, etc. That's probably a lot of overhead you just saved.

12. Config Changes Not Reflected

Browser cache. your configuration may be perfect but you'll sit there and beat your head against a cement wall for a month. what's wrong is your browser cache. when you download something, your browser stores it. it also stores how that file was served. if you are playing with a types {} block you'll encounter this.

The fix:

  • In Firefox press Ctrl + Shift + Delete, check Cache, click Clear Now. in any other browser just ask your favorite search engine. do this after every change (unless you know it's not needed) and you'll save yourself a lot of headaches.
  • Use curl.
13. VirtualBox

If this does not work, and you're running NGINX on a virtual machine in VirtualBox, it may be sendfile () that is causing the trouble. simply comment out the sendfile directive or set it to "off ". the directive is most likely found in your nginx. conf file.:

sendfile off;
13. Missing (disappearing) HTTP Headers

If you do not explicitly setUnderscores_in_headers on, NGINX will silently drop HTTP headers with underscores (which are perfectly valid according to the HTTP standard ). this is done in order to prevent ambiguities when mapping headers to CGI variables as both dashes and underscores are mapped to underscores during that process.

14. Not Using Standard Document Root Locations

Some directories in any file system shoshould never be used for hosting data from. Some of these include/Androot. You shoshould never use these as your document root.

Doing this leaves you open to a request outside of your expected area returning private data.

Never do this !!! (Yes, we have seen this)

server {    root /;    location / {        try_files /web/$uri $uri @php;    }    location @php {        [...]    }}

When a request is made for/foo, the request is passed to php because the file isn' t found. this can appear fine, until a request in made for/etc/passwd. yup, you just gave us a list of all users on that server. in some cases, the NGINX server is even set up run workers as root. yup, we now have your user list as well as password hashes and how they 've been hashed. we now own your box.

The Filesystem Hierarchy Standard defines where data shocould exist. You shocould definitely read it. The short version is that you want your web content to exist in either/var/www/,/srv,/usr/share/www.

15. Using the Default Document Root

NGINX packages that exist in Ubuntu, Debian, or other operating systems, as an easy-to-install package will often provide a 'default' configuration file as an example of configuration methods, and will often include a document root to hold a basic HTML file.

Most of these packaging systems do not check to see if files are modified or exist within the default document root, which can result in code loss when the packages are upgraded. experienced system administrators know that there is no expectation of the data inside the default document root to remain untouched during upgrades.

You shoshould not use the default document root for any site-critical files. there is no expectation that the default document root will be left untouched by the system and there is an extremely high possibility that your site-critical data may be lost upon updates and upgrades to the NGINX packages for your operating system.

16. Using a Hostname to Resolve Addresses

BAD:

upstream {    server http://someserver;}server {    listen myhostname:80;    # [...]}

You shoshould never use a hostname in a listen directive. while this may work, it will come with a large number of issues. one such issue being that the hostname may not resolve at boot time or during a service restart. this can cause NGINX to be unable to bind to the desired TCP socket which will prevent NGINX from starting at all.

A safer practice is to know the IP address that needs to be bound to and use that address instead of the hostname. this prevents NGINX from needing to look up the address and removes dependencies on external and internal resolvers.

This same issue applies to upstream locations. While it may not always be possible to avoid using a hostname in an upstream block, it is bad practice and will require careful considerations to prevent issues.

GOOD:

upstream {    server http://10.48.41.12;}server {    listen 127.0.0.16:80;    # [...]}
17. Using SSLv3 with HTTPS

Because of the POODLE vulnerability in SSLv3, we recommend that you disable it on an SSL website, instead of using the TLS Protocol only.

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 

Original article: https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.