nginxurl-rewritingamp-html

Nginx - Rewrite URL containing amp/ to remove amp/ from the end


I am using wordpress and installed an AMP plugin last week. After playing with it for a bit, I decided to remove it until Google makes AMP prominent for non news sites as well.

In the time it was installed, some of my AMP pages got shared on social media and now visitors come to my site to AMP URLs. They see the original page but the URL stays and gets shown in Google Analytics as a separate page from the non AMP version.

I think they're also hitting my server directly instead of cache and it's putting a heavy load on my server.

My AMP URLs look like:

www.mysite.com/category/this-is-my-post/amp/

I'm not well versed in nginx rewrites and don't understand the syntax properly.

How do I get that example URL to just be:

www.mysite.com/category/this-is-my-post/

This is the nginx rewrite code I have so far and it's not doing anything at all. What am I doing wrong here?

location /amp {
    rewrite ^/amp(/.*)$ $1 last;
}

and I also tried this:

rewrite ^/amp/(.*)$ http://www.myserver.com/$1 last;

These solutions seem to take /amp/ out of the URL if it's somewhere in the middle, not at the end. When amp is at the end it refuses to get redirected.

Also, if there are GET parameters (for tracking or anything else), I'd like them to stay and not be re-written.

Thank you!


Solution

  • You need to remove the amp/ sequence from the end of the URL.

    rewrite ^(.*/)amp/$ $1 permanent;