Nginx – How to Avoid Redirecting POST to GET

nginx

I am see this in my log

"POST /openDoor HTTP/1.1" 301 169 "-" "PostmanRuntime/7.29.0"

"GET /openDoor/ HTTP/1.1" 200 113 "https:///openDoor" "PostmanRuntime/7.29.0"

I am doing a POST to /openDoor and I get a 301. why?

My nginx conf file is this

server {

    client_body_buffer_size 30M;
    client_max_body_size 30M;


    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;

        proxy_buffer_size          1024k;
        proxy_buffers              32 2048k;
        proxy_busy_buffers_size    2048k;
    }


    location / {
        index index.php;
        try_files $uri $uri/ /index.php?q=$uri&$args =404;
    }


    error_log   /var/log/nginx/error.log  warn;
    access_log  /var/log/nginx/access.log combined;

    server_name <redacted>;

    root /var/www/project;


    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/<redacted>/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/<redacted>/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

How to avoid this strange redirect?

I tried this, without any results

location /openDoor {
  add_header Cache-Control no-cache;
  expires -1;
  add_header Cache-Control no-store;
  try_files /openDoor/index.php =404;
}


location /openDoor/ {
  add_header Cache-Control no-cache;
  expires -1;
  add_header Cache-Control no-store;
  try_files /openDoor/index.php =404;
}

Best Answer

Since openDoor is a physical directory, it is nginx that does that 301 /openDoor to /openDoor/ redirect and with the HTTP 301 redirection user browser will change the request method from POST to GET abandoning the request body. You can try to specify the HTTP 308 redirect explicitly with the

location = /openDoor {
    return 308 $request_uri;
}

Although is isn't directly related to your question, you should replace the

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

line with the

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

The reason is that try_files directive processed the files with the location block context, and since you don't have a FastCGI handler in that location your index.php file will be served as a plain text. On the other hand the very last try_files parameter will be treated as a new URI and the right location ~ \.php$ { ... } will be chosen to serve it.