简体   繁体   中英

Hiding true URL from website visitor

I have a php website. The various pages are distributed in various directories. Now, when I try to send the link to any page to a user, I have to put some URLs like "www.mydomain.com/collection/latest/requestpage.html" or "www.mydomain.com/api/get/someapi.php" . But this URL is too complicated. I want the pages to be referred via the URLs like "www.mydomain.com/collection/requestpage" and "www.mydomain.com/someapi" and also this same address to be displayed in the url bar of browser.

Thus, loading "www.mydomain.com/collection/requestpage" takes the user to "www.mydomain.com/collection/latest/requestpage.html" and loading "www.mydomain.com/someapi" takes the user to "www.mydomain.com/api/get/someapi.php" .

So,

1) I want the actual directory structure to be hidden from the URL,

2) I want to hide the file type extension of the page being loaded, and

3) Show this modified URL in the address bar of the browser when accessing the specified page.

I know this can be done using a .htaccess file but I have never written anything like this before. I have a .htaccess file on my directory that redirects any request coming to "mydomain.com" to "www.mydomain.com". I want to add some code to this htaccess file to do the tasks I mentioned. Please suggest what requires to be done.

Thanks in advance.

1) to remove the directories from the URL just add the following codes to your .htaccess file

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^FOLDER_NAME/ FOLDER_NAME%{REQUEST_URI} [L,NC]

Change FOLDER_NAME with your actual folder names

2) to remove extensions from the URL use following code

RewriteEngine on
RewriteBase /

for html

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

for php

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]

EDIT: while working with POST requests you have to change the RewriteRule as following

RewriteRule ^ %1 [R=307,L]

3) You are done with what you wanted

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM