Rewrite nginx for clean urls

What I'm trying to accomplish is to have people who go: http://www.example.com/ $ SEARCH-QUERY / $ PAGE-NUMBER to redirect to search.php? query = SEARCH-QUERY & page = PAGE-NUMBER

I just figured out how to install nginx and configure php-fpm, mysql and all, but now I'm a bit confused by the rewritings. Here is what I have that does not work correctly:

The PHP script will automatically take it to the first page if a page request is not sent with it, I also had to follow two rewrite rules, because I could not figure out how to implement it on one line, so that it could have it with a trailing slash and without her.

rewrite ^/search/(.*)$ /search.php?query=$1; rewrite ^/search/(.*)$/ /search.php?query=$1; 

and then for items viewed with paginated results

 rewrite ^/search/(.*)/(.*)$ /search.php?query=$1&page=$2; rewrite ^/search/(.*)/(.*)$/ /search.php?query=$1&page=$2; 

If anyone could help, I would really appreciate it!

+4
source share
2 answers

You have a major mistake in your regular expressions.

^/search/(.*)$/ will never match, because $ means "end of line". You cannot have / after the end of a line.

If you need extra / , is there a modifier in regexes ? .

So try /search/(.*)/?$ .

+3
source

In addition, your first regular expression ^/search/(.*)/?$ will match all queries starting with /search/ : it will call the page number in the search string, and also because * includes an empty string, it will match zero search strings. If the second regex ^/search/(.*)/(.*)/?$ appears later, it will never be matched. If you want to grab the string to the first slash, use ^/search/([^/]+)/?$ And ^/search/([^/]+)/([^/]+)/?$ (So that wildcards match strings of characters, not including / , and not strings of all characters, but + matches one or - more than any number).

+1
source

All Articles