Home > Software engineering >  php nginx rewrite urls to index.php with
php nginx rewrite urls to index.php with

Time:08-19

I've been trying to get this to work for a while now, but I'm failing manifold.

I have the following configuration:

server {
        listen 8081;
        server_name name.of.server.en;
        root /path/to/api;
        index index.php;

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        }

        location / {
                try_files $uri $uri/ @rewrite;
        }

        location @rewrite {
                rewrite ^/([A-Za-z0-9] )/$ /index.php?data=$1? last;
                rewrite ^/([A-Za-z0-9-] )/([A-Za-z0-9-] )/$ /index.php?data=$1&id=$2? last;
                return 404;
        }
}

nginx -t says that everything is ok. But as soon as I call the URL I always get a 404 Not Found.

I have no idea what I am doing wrong. Probably something completely banal, but I can't figure it out. I am almost at the despair.

CodePudding user response:

Here is what I am running for PHP7.4 for local testing. Might be helpful to you.

server {

    listen 80;
    root /var/www/html/public;
    index index.html index.php;
    server_name fancyproject;

    charset utf-8;

    location / {
        root /var/www/html/vue/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt { access_log off; log_not_found off; }

    add_header "Access-Control-Allow-Origin"  *;
    add_header "Access-Control-Allow-Methods" "GET,POST,OPTIONS,HEAD,PUT,DELETE,PATCH";
    add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept, X-Nonce, DNT, X-CustomHeader";

    access_log off;
    error_log /var/log/nginx/error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ .php$ {
        fastcgi_split_path_info ^(. .php)(/. )$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    location ~ /.ht {
        deny all;
    }
}

CodePudding user response:

The order is important at this point. This is how it should work:

server {
        listen 8080;
        server_name the.server.name.org;
        root /path/to/api;
        index index.php;

        location / {
                rewrite ^/(.*)$ /index.php?data=$1 last;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        }
}
  • Related