Nginx URL rewrite - nginx

I have a website that has laravel setup to run under http://www.example.com/lara/
So, most Laravel pages have URLs of type http://www.example.com/lara/page/23 OR http://www.example.com/lara/category/23 etc.
Nginx is the underlying server and it has the following configuration to handle these requests:
location /lara/ {
try_files $uri $uri/ /lara/index.php?$query_string;
}
Everything works ok.
Now, I need to setup a special page with the URL http://www.example.com/mystuff/ which actually is handled by
http://www.example.com/lara/category/29
To get this working I added the following rewrite right below location /lara/, that is:
rewrite ^/mystuff/(.*)$ /lara/category/29/$1 last;
Unfortunately, I get a page not found error. Any insights?
Further investigation & research:
1)
location /mystuff/ {
return 301 /lara/index.php/category/29;
}
worked although that's not (browser address bar changes to) what I actually want.
2) Looks like Laravel is not seeing the updated REQUEST_URI.

Try this
server {
...
rewrite ^/lara/(.*)\..*$ $1/mystuff last;
return 403;
...
}

Related

Nginx, nuxt.js static generated mode and redirection of trailing slashs

i currently have a problem configuring my Nginx correctly for nuxt.js generated sites.
What i want to achieve is the following
/magazin -> /magazin/index.html
/magazin/ -> 301 /magazin
/magazin/artikel/titel-goes-here -> /magazin/artikel/titel-goes-here/index.html
/magazin/artikel/titel-goes-here/ -> 301 /magazin/artikel/titel-goes-here
currently this is the other way around.
If im correct i shouldn't use a proxy pass to a e.g. pm2 instance with express etc. as it destroys the sense of static site generation.
But how can i get this page structure to work, as i need the same url's as our legacy service for SEO reasons, which used Angular Universal SSR
my current config is:
location ^~ /magazin {
root /path/to/dist;
index index.html ;
}
if i add something like
rewrite ^(.+)/+$ $1 permanent;
i get an infinite 301 loop
Thanks for the help
You cannot use the built in index directive, as it works the other way around (as you have observed).
You can use try_files to test for the existence of the index.html file. Use a named location to process the redirection.
For example:
location ^~ /magazin {
root /path/to/dist;
try_files $uri $uri/index.html #rewrite;
}
location #rewrite {
rewrite ^(.+)/$ $1 permanent;
}
See this document for details.

Removing path from urls in Nginx

My site works correctly as
https://example.com/website/page/Home
https://example.com/website/page/AboutUs
I would like to remove the /website/page part so that end users would see https://example.com/Home etc.
I read on Nginx website that rewrites are not preferred so I tried:
Location / {
try_files $uri /website/page$uri;
}
I get an internal serval error. What is the right way?
Consider using a rewrite like:
# rewrite example.com/awesome to example.com/website/page/awesome
rewrite ^(/.*) /website/page$1 break;
This should work similarly:
rewrite ^/(.*) /website/page/$1 break;

NGINX try_files works for all but one url

I have a simple dashboard for my site. Here is the directive:
location /dashboard {
try_files $uri /dashboard/index.php;
}
It works for all items after /dashboard. For example, /users or /pages - all CRUD operations work as expected.
The index.php file at /dashboard is my "controller". It parses the url and includes and runs scripts from there.
For example: /dashboard/group/edit/123456 works as expected and I get the edit page for group number 123456.
But when I post from that page to /dashboard/group/update, it serves /dashboard/group/index.php
So, in the first example, The edit page is loaded and the url at the top of the screen does not change.
In the second example, NGINX is CHANGING the url so my script cannot get the url parts to do the job.
I thought it may have something to do with POST, but I have other forms that use POST without issue.
In addition, or possibly a clue, try_files is returning /dashboard/group/index.php while the directive should return /dashboard/index.php.
Is there another NGINX file that could have so old code in it that is overwriting this domain's config?
I've been at this a few hours and have run out of ideas. Any thoughts?
* One More Clue *
When I BROWSE to /dashboard/group/update, NGINX shows the page as expected. It is only when I POST to that page that NGNIX sends me to /dashboard/group/index.php.
Again, at the very least, it should be sending me to /dashboard/index.php and NOT /dashboard/group/index.php.
You not send all after /dashboard try this:
location /dashboard {
try_files $uri /dashboard/index.php?$uri&$args;
}
OR
location /dashboard {
try_files $uri /dashboard/index.php?$query_string;
}
Nginx docs: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
Instead of
location /dashboard {
try_files $uri /dashboard/index.php;
}
Try
location /dashboard {
index index.php; #adding this may work alone
try_files $uri /dashboard/index.php?$uri;
}
I have concluded that I have a cache problem. The location directive works on all items that I have not yet accessed.
So, my configuration - as described - works as it should.
I just have to figure out how to clear my cache ( which in NOT set up in NGINX that I can see!)
Thank you all who helped!

How to handle 404 error request in vuejs SPA with nginx server

I have set up my vue-cli version 3 SPA so that any requests not found in my routes.js file will default to my 404 view as shown in the official documentation:
Inserted near bottom of routes.js file:
{ // catches 404 errors
path: '*',
name: '404',
component: () => import(/* webpackChunkName: "NotFoundComponent" */ './views/NotFoundComponent.vue'),
},
Inserted into nginx configuration file:
location / {
try_files $uri $uri/ /index.html;
}
This successfully alerts the user that the page they requested doesn't exist.
My Question:
I would like for the error 404 component to return a 404 response header (it current returns the 200 status code) and also log this error to the nginx error.log file. I imagine this is only possible through using nginx configuration. Has anyone achieved this goal?
I noticed that this issue is addressed in the following page in the vue-cli official docs, but it only is concerned with node express servers and not nginx:
https://router.vuejs.org/guide/essentials/history-mode.html#caveat
I think it is similar to Node solution - you should repeat all your routes in nginx config to return 404 status code correctly, the main idea is that you should use "equals" modifier in locations and define error_page to return same index.html file but with 404 status code, example:
server {
listen 80;
server_name localhost;
root /my/dir/with/app
error_page 404 /index.html;
location = / {
try_files $uri $uri/ /index.html;
}
location = /books {
try_files $uri $uri/ /index.html;
}
# example nested page
location = /books/authors {
try_files $uri $uri/ /index.html;
}
# example dynamic route to access book by id
location ~ /books/\d+$ {
try_files $uri $uri/ /index.html;
}
}
Probably this config can be simplified or improved because I am not very good at nginx configuration but it works.
I solved this the easy way by breaking out of the Vue ecosystem else it wont work or would take a lot of effort.
Make the following route in your Vue router:
{
path: '*',
name: 'PageNotFound',
component: PageNotFound
}
The PageNotFound component should have the following code:
<script>
export default {
name: 'PageNotFound',
created() {
window.location.href = "/404/"
}
}
</script>
The nginx config should return a 404 on getting /404/ route:
server {
...
location ~ ^/404/$ {
return 404;
}
...
}
I don't think it would work in a server side rendering environment. In such a case you might need to put the statement containing window.location.href in the mounted method.
For whoever lands into this issue and to save you hours of headaches.
Caveats with above answers
Simply reloading the page with a new URL (e.g. /notfound) does not solve it since that means that a potential spider already received 200.
Simply copying the routes, is a half-solution. That works with URLs that are never going to change and by checking the validity of the URL structure. So for example it can check if the book id in books/123 has the right format, but it can't check if books/123 actually exists in the backend.
Here's two approaches that can tackle the above issues
Have Nginx to make a mirrored subrequest to the backend to check if the resource actually exists. Then always return index.html but with the status from the subrequest's response. This is very tricky with Nginx, since by design it makes it very hard to combine answers.
Have the backend API to return index.html for Accept: text/html. Then Nginx simply needs to forward responses.
The first solution is a pain in the ass for someone not familiar with Nginx. It requires to get Lua with OpenResty and then again you will run into all kinds of quirks with how Nginx works. You end up with a lot of hard-to-read code and that makes it extra hard if you further-more want to introduce caching.
The second solution is easier. The only possible negative is that it means that you can't view the API from the browser if that's something currently you have in place.
nginx.config (when API responds with index.html on Accept: text/html)
location / {
try_files $uri $uri/ #fallback;
}
location #fallback {
rewrite ^(.*) /api$1 break;
proxy_set_header "Accept" "text/html";
proxy_pass http://localhost:8000;
}
In this case, Nginx will try first to serve the file and in case it doesn't find it locally, it will go through the fallback.
In the fallback we rewrite the URI to match what the backend server expects. In this example I prepend api/ to each request. Then I add the header Accept: text/html so that the backend API will respond with the index.html instead of JSON. And lastly we directly give back the response to the client.
This has the below benefits:
It does not rely on Nginx so it can work with any reverse proxy. Most importantly it does not rely on the proxy server to have certain features.
Works even during development without having Nginx running.
Easy to write tests for. You simply have to test your backend API for spitting out index.html when given Accept: text/html for any endpoint.
Does not require you to manually update Nginx configuration with each new endpoint.
Furthermore you can change the config to make Nginx follow redirects internally, and possibly not even having to look at the backend API for URLs that never change.

Nginx redirect setting

My Nginx setting currently has this:
location / {
if (!-e $request_filename){
rewrite ^/(.*)$ https://domain.com/index.php?id=$1 redirect;
}
}
Basically for non-existing pages (404) it redirects user to the home page. But now I have a wordpress blog setup at https://domain.com/blog/, but any wordpress items eg. https://domain.com/blog/test also got redirected to the home page. I wonder how to fix this?
to do something different for requested url's whose path starts with '/blog/' add a corresponding location like so:
location / {
if (!-e $request_filename){
rewrite ^/(.*)$ https://domain.com/index.php?id=$1 redirect; }
}
location /blog/ {
#add in whatever directives are needed to serve your wordpress
}
You shouldn't be using an if. Please read the IfIsEvil page on the nginx wiki. Instead you should be using try_files.
Your config should look more like this:
location / {
try_files $uri $uri/ #notfound
}
location #notfound {
rewrite ^(.*)$ https://domain.com/index.php?id=$1 redirect;
}
Really, you shouldn't be doing this at all. Instead you should be setting a custom error page. Redirecting every 404 to the home page is bad for your SEO.
Edit: I just realized you were passing the URL into "id". So I removed my second comment about using . instead of ^(.*)$. Still an error page is your best bet. You can pick up the URL with $_SERVER['REQUEST_URI'] (if you avoid the hard redirect).
This page has some sample configurations that may be helpful to you. It has a few wordpress configs.

Resources