Substituting the URL only if the file was found using mod_rewrite

this is how i do it:

  • user enters URL
  • mod_rewrite processes the URLs of the form: ^([^/\.]+)/?$ (first segment on the way)
  • and redirect them to the index page: struct.php?page=$1
  • on the index page (struct.php) I request the contents of the page ($ _GET ['page']) if it exists:

    $content = @file_get_contents("pages/$_GET[page]/.content")

  • If the content does not exist, I simply request the contents of the 'not_found/.content' page

This works, but I would like to make things simple in the script and use the power of mod_rewrite to query only existing pages.

here is how i would like to do:

  • user enters URL
  • mod_rewrite processes the URLs of the form: ^([^/\.]+)/?$ (first segment on the way)
  • and redirect them to the index page only if the .content file is .content : struct.php?page=$1

here is my attempt:

 <IfModule mod_rewrite.c> RewriteEngine on RewriteCond pages/$1/.content -f RewriteRule ^([^/\.]+)/?$ struct.php?page=$1 [L] </IfModule> 

note : i am using a .htaccess file

+4
source share
2 answers

Here is my solution:

 RewriteEngine On RewriteCond %{REQUEST_URI} ^([^/\.]+)/? RewriteCond %{DOCUMENT_ROOT}/%1/.content -f RewriteRule ^([^/\.]+)/? struct.php?page=$1 [PT,QSA,L] 
+1
source

Have you tried the following?

 RewriteEngine on RewriteCond %{QUERY_STRING} ^([^/\.]+)/? RewriteCond /absolute/path/pages/$1/.content -f RewriteRule ^.*$ struct.php?page=$1 [PT,QSA,L] 

I have not tested this, so I'm not sure if it works, but you should try.

Remember the change / absolute / path / to the absolute path to the page folder.

0
source

Source: https://habr.com/ru/post/1380909/


All Articles