1

I have a site and i wish to replace a part of URL, https://example.com/[THISPART]/file.ext.

Example URLs that will be requested on site:

https://example.com/example-page/sw.js
https://example.com/example-page/image.jpg
https://example.com/some-other-page/sw.js
https://example.com/some-other-page/file.pdf
https://example.com/page-with-attitude-4/sw.js
https://example.com/page-with-attitude-4/info.txt

How I want to rewrite them:

https://example.com/content/example-page/sw.js
https://example.com/example-page/image.jpg
https://example.com/content/some-other-page/sw.js
https://example.com/some-other-page/file.pdf
https://example.com/content/page-with-attitude-4/sw.js
https://example.com/page-with-attitude-4/info.txt

In other words, if only sw.js is requested, then rewrite to other URL. What I have used so far in my htaccess is this:

RewriteRule ^(.*)\/sw.js$ content/$1/sw.js [L]

I've been using http://htaccess.mwl.be/ as a tester and test shows alright, but when I use it on site, it doesn't work. Any help?

2 Answers 2

1

Put the folowing code at your main directory .htaccess file :

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} sw\.js 

#the line above to match sw.js

RewriteCond %{THE_REQUEST} !content

# the line above to exclude any request including content from the following rule

RewriteRule ^(.*)$ content/$1 [R=302,L,NE]

#the line above to apply redirection for requests that passed previous conditions and redirect any request ended with sw.js 

RewriteRule ^content/(.*)$ /$1 [L,QSA]

#the last line is to make internal redirection for original path

After testing , if it is Ok , change 302 to 301 if you wanna make permanent redirection

Sign up to request clarification or add additional context in comments.

1 Comment

Since I made it with just RewriteRule earlier, I'll keep that for now, but thanks a lot! :)
1

Made it!

RewriteRule ^([A-Za-z-]+)/sw\.js$ /places/$1/sw.js [L,QSA]

2 Comments

Crucially, the modified RewriteRule pattern (ie. ([A-Za-z-]+)) matches just a single path segment, so prevents a rewrite loop. (The QSA flag is not required here - the query string is appended by default.)
@MrWhite, found out the same. Always these thing that you don't work with everyday steal the most time in a project :) After reading regex documentation, trial and error for few hours - came to the same conclusion. Since I was using that webiste for testing and it showed no error, thought my first Rewrite rule was correct. Now I know that website is not all-that-good. Anyways, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.