1

I have these .htaccess rewrite rules on my .htaccess file:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /site/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  # RewriteRule ^materia/([^/]+)/?$ article.php?slug=$1 [L,NC]
  RewriteRule ^([^/]+)/?$ index.php?slug=$1 [L]
</IfModule>

Inside a PHP class, I have a function which detect if URL have a specific variable:

if (isset($_GET['slug'])) {
  $slug = $_GET['slug'];
  $file = 'partials/'.$slug.'.php';
} else {
  $slug = 'home';
  $file = 'partials/home.php';
}

It's working fine. But when I remove the # from the second rule, the function start to return index.php as a value from variable slug when the URL is http://website.test/site/

Justin Iurman
  • 18,954
  • 3
  • 35
  • 54
marcelo2605
  • 2,734
  • 4
  • 29
  • 55
  • This seems like the intended behavior. Since your site base is `/site/` and no slug is specified outside of that, the page to load will be `index.php`. What is the undesired behavior in this case? Are you expecting there to be no `$_GET['slug']` property?... – War10ck Jul 23 '18 at 15:59
  • @War10ck The script load the correct file (index.php), but since no slug is added after `/site/` I expect $_GET['slug'] is not set. – marcelo2605 Jul 23 '18 at 16:03
  • If I type http://website.test/site/materia/foo, the slug value is still index.php when the expected value is foo. – marcelo2605 Jul 23 '18 at 16:05

1 Answers1

1

But when I remove the # from the second rule, the function start to return index.php as a value from variable slug when the URL is http://website.test/site/

Please refer to my answer on your previous question (https://stackoverflow.com/a/51479577/3181248). Indeed, RewriteCond is only applied to the very next (uncommented) RewriteRule. When you uncomment it, there is a transparent infinite rewrite loop because of that ==> last rule matches index.php again and again, since the folder/file condition is not applied to it.

Actually, here is how your /site/.htaccess (please make sure it is located in that folder) should look like

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /site/

  # if either a physical folder or file, don't touch it
  RewriteCond %{REQUEST_FILENAME} -f [OR]
  RewriteCond %{REQUEST_FILENAME} -d
  RewriteRule ^ - [L]

  # your rules here...
  RewriteRule ^materia/([^/]+)/?$ article.php?slug=$1 [L,NC]
  RewriteRule ^([^/]+)/?$ index.php?slug=$1 [L]
</IfModule>

Note: of course, both files article.php and index.php should be in /site/ folder too.

Justin Iurman
  • 18,954
  • 3
  • 35
  • 54