Home > Net >  .htaccess RewriteRule with two different conditions
.htaccess RewriteRule with two different conditions

Time:10-27

I have two different URLs:

1.: mysite.com/file.php

2.: mysite.com/**articles**.php?article=**something**

I would like to rewrite mysite.com/file.php to mysite.com/file.

AND

I would like to rewrite mysite.com/**articles**.php?article=something to mysite.com/**news**/**something**

I tried this but it's not working.

It rewrite mysite.com/file.php to mysite.com/file, but does not rewrite mysite.com/**articles**.php?article=**something** to mysite.com/**news**/**something**

RewriteEngine On 
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^?\ ] )\.php 
RewriteCond %{REQUEST_FILENAME} !exception.php 
RewriteRule ^news/([^/] )(/*)$ /articles.php?article=$1 
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301] 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*)$ /$1.php [L]

(There is one exception in the code: exception.php which I don't want to rewrite.)

Can you please correct my code? I've been working on this for 4 days, I've read everything, but I can't do it.

CodePudding user response:

With your shown samples and attempts please try following .htaccess rules file. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteCond %{REQUEST_URI} !/?exception\.php [NC]
RewriteCond %{THE_REQUEST} \s/(file)\.php/?\s [NC]
RewriteRule ^ /%1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$ $1.php [QSA,L]

RewriteCond %{THE_REQUEST} \s/articles\.php\?article=(\S )\s [NC]
RewriteRule ^ /news/%1? [R=301,L]
RewriteRule ^news/([^/]*)$ articles.php?article=$1 [NC,QSA,L]
  • Related