Home > Back-end >  Use .htaccess to redirect to directory URL but show the URL as if in root
Use .htaccess to redirect to directory URL but show the URL as if in root

Time:03-26

I currently have a CRUD that has the following file structure:

enter image description here

The index.php file redirects to the add-product.php, delete.php and other files. The problem is, the URL looks like: myapp.com/resources/views/add-product but I want it to look like myapp.com/add-product. I found other StackOverflow posts similar to this, but it redirects to the desired link, instead of redirecting to the correct link but showing the desired one, and because of that the site doesn't work ("The requested URL was not found on this server"). The .htaccess file looks like this:

Options  FollowSymLinks  MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.] )$ $1.php [NC,L]
RewriteRule ^resources/(.*)$ /$1 [L,NC,R]

I'm also using the file to be able to remove the .php from the URLs. The last line is the one handling the wrong redirection. How can I go about this? Thank you for your time.

CodePudding user response:

You may use it like this:

Options  FollowSymLinks  MultiViews
RewriteEngine On
RewriteBase /myapp/

# external redirect to remove /resources/views/ from URLs
RewriteRule ^resources/views/(. )\.php$ $1 [L,NC,R=302]

# internal rewrite to add /resources/views/ and .php to show content
RewriteCond %{DOCUMENT_ROOT}/myapp/resources/views/$1.php -f
RewriteRule ^(. ?)/?$ resources/views/$1.php [END]

Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.

  • Related