简体   繁体   中英

How can I make this php redirect not be conflicted by Nginx

My php file 404.php contains a php redirect at the top of the file:

<?php
    header('Location: some-page.html');

If I go to www.mysite.com/404, it redirects to www.mysite.com/some-page.html as expected, however, if I go to www.mysite.com/non-existent-page, the redirect does not work.

In my nginx.conf :

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

error_page 404 =200 /404.php;

try_files $uri @remExt;
location @remExt {
    rewrite ^(.*)$ $1.php last;
}
if ($request_uri ~ ^/([^?]*)\.php($|\?)) {
    return 301 /$1$is_args$args;
}
rewrite ^/index$ / permanent;
rewrite ^/(.*)/$ /$1 permanent;

How can I make the php redirect work when visiting www.mysite.com/non-existent-page?

PS

Sorry for the badly written question title. The clear and better written question title I wanted to use was automatically rejected.

Try this in your nginx config and restart it.

error_page 404 /404.php;
location = /404.php {
    root /path/to/www/;
    internal;
}

/404.php

<?php
    http_response_code(301);
    header('Location: /the/page/you/want');

nginx.conf

error_page 404 /404.php
location / {
    try_files $uri $uri.php $uri/ =404;
}

then check syntax with nginx -t and reload nginx with systemctl reload nginx (if you're using systemd)

http://php.net/manual/en/function.http-response-code.php

It appears I have solved the problem, although there may be some edge cases where my Nginx code fails.

The problem was with this line error_page 404 =200 /404.php; . The solution is to use try_files inside location ~* \\.php$ .

index index.php;

location ~* \.php$ {
    try_files $uri $uri/ /404.php$is_args$args;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm-root.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location / {
    try_files $uri $uri/ $uri.php$is_args$query_string;
}

if ($request_uri ~ ^/([^?]*)\.php($|\?)) {
    return 301 /$1$is_args$args;
}
rewrite ^/index$ / permanent;
rewrite ^/(.*)/$ /$1 permanent;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM