Questioner
Questioner

Reputation: 7463

Why is this one rewrite rule in my NginX conf file breaking my site?

I'm trying to set up an NginX rewrite rule so that I can take the following URL:

http://example.com/xyz/

... and parse it so that xyz is taken as the value of a variable that I can use in PHP.

I have this rewrite rule:

rewrite ^/(.*)/ /index.php?var=$1 last;

However, this seems to break my site. When the site first loads, so the URL is just http://example.com/, and there is no variable set, none of my JavaScript or CSS files are found. If I comment out this one rewrite line, then my site works fine.

How do I set my rewrite rule to not break my site when no variable is set? Note that the value of var is always a three letter code, if that helps constrain it.

Upvotes: 1

Views: 35

Answers (1)

Richard Smith
Richard Smith

Reputation: 49842

Your rewrite rule is matching nearly everything. Any URI with a second / (not even at the end) will match your rule.

You need to restrict the regular expression to match only the URIs you are interested in.

To match any URI that ends with a / (e.g. /foo/ and /foo/bar/), you need the $ anchor: ^/(.*)/$

To match only the first path element (e.g. /foo/ but not /foo/bar), use a character class which excludes /: ^/([^/]*)/$

To match a three letter code, use \w to match word characters and {} syntax to indicate the length. nginx requires the regular expression to be quoted if it contains {} characters: "^/(\w{3})/$"

See this useful resource on regular expressions.

Upvotes: 1

Related Questions