Score:0

how do I redirect a location to another but not changing its URL in Nginx

co flag

I am working on a website to display different products, users can access different product page by urls like 'mydomain.com/product/1.html', 'mydomain.com/product/2.html'

but I don't want to present those static html files directly, instead there is a php script will be loaded first at mydomain.com/product.php

so I want to redirect 'mydomain.com/product/1.html' to 'mydomain.com/product.php' but don't change its original url

I tried alias, try_files, return, but all of them rewrite the url to 'mydomain.com/product.php'

I am new to Nginx, this is probably a very simple question, but I have tried to achieve this for couple of days.

Score:0
gr flag

There are so many ways to do it...

The most simple is

rewrite ^/product/ /product.php;

at the server context. Your original request URI (i.e. /product/1.html) will be available for product.php script as $_SERVER['REQUEST_URI'] array item value.

You can also use rewrite directive at the location context, this can be slightly (very slightly) more performant:

location /product/ {
    rewrite ^ /product.php last;
}

If you want, you can get product code and pass it to your product.php script as a query argument:

rewrite ^/product/(.*)\.html$ /product.php?product=$1;

or

location /product/ {
    rewrite ^/product/(.*)\.html$ /product.php?product=$1 last;
}

This way your product code (1 for the /product/1.html URI, 2 for the /product/2.html URI, etc.) will be available for product.php script as $_GET['product'] array item value.

You can even define an individual FastCGI handler for this:

location /product/ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/product.php;
    fastcgi_pass <fastcgi_upstream_or_socket>;
}

(original request URI will be available via $_SERVER['REQUEST_URI']), or if you want for product code to be available via $_GET['product']:

location ~ /product/(.*)\.html$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/product.php;
    fastcgi_param QUERY_STRING product=$1;
    fastcgi_pass <fastcgi_upstream_or_socket>;
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.