Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

apache - Replace query string with file extension using htaccess Rule

I have this link https://career.guru99.com/top-50-c-sharp-interview-questions-answers/?format=pdf

I want to redirect it to https://www.guru99.com/pdf/c-sharp-interview-questions.pdf

I created the following htaccess rule

RewriteCond %{QUERY_STRING} format=pdf [NC]
RewriteRule ^c-sharp-interview-questions.html  /pdf/c-sharp-interview-questions.pdf? [R=301,L]

But the challenge is I have 100+ links and I will have to manually add so many entries in the htacess which also slow down the site. Is there some regular expression that can help with this?

I want /?format=pdf to be replaced with .pdf


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1st Solution: Try following in case you are hitting http://localhost:80/top-50-c-sharp-interview-questions-answers/?format=pdf in your browser. Change [NC,L] TO [R=301,NC,L] in case you want to redirect your URL in browser.

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^career.guru99.com$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{QUERY_STRING} ^format=(.*) [NC]
RewriteRule ^top-50-(.*)/?$ pdf/c-sharp-$1.%1 [NC,L]


2nd solution: Could you please try following, written based on your shown samples(considering that you want to hit http://localhost:80/pdf/c-sharp-interview-questions.pdf in your browser).

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^career.guru99.com$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

RewriteRule ^(pdf)/([^.]*).(pdf)/?$ top-50-$1/?format=$2 [NC,L]

NOTE: Either use 1st OR use 2nd solution at a time please. Please make sure you clear your browser cache before testing your URLs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...