Remove File Extension and URL Variable using .htaccess - php

I'm making up myself a small blog and I found a useful .htaccess file to remove file extensions:
AddType text/x-component .htc
RewriteEngine On
RewriteBase /
# remove .php; use THE_REQUEST to prevent infinite loops
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
# remove index
RewriteRule (.*)/index$ $1/ [R=301]
# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]
# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php
This works just fine and all pages are showing up .php less. I know wanted to extend this so when I click a link to a specific blog post (say /blog/index.php?art=1) it just shows in the url as website/blog/1. I thought to tag on to the end of the .htaccess file:
RewriteRule ^blog/(.*)$ blog/index.php?art=$0 [L]
But that doesn't seem to be working. EDIT Actually it breaks the blog page so no snippets are pulled through from the DB
My .htaccess file is in the root directory and the blog files are /root/blog/index.php
Any help would be gratefully appreciated

Unlike most other languages, the parameters in .htaccess are not 0-based. To access the first parameter, you should use $1, not $0.
The following should work:
RewriteRule ^blog/(.*)$ blog/index.php?art=$1 [L]
It might also be worthwhile to add some tests in there, for example you might only want numerical values passed to art, so you can improve it using:
RewriteRule ^blog/([0-9]+)$ blog/index.php?art=$1 [L]
Also, it might be worthwhile to add the QSA flag, since this will also preserve any query string that is passed in the original URL:
RewriteRule ^blog/([0-9]+)$ blog/index.php?art=$1 [L,QSA]

Related

How to apply mod_rewrite rules to files within directory?

I'm trying to apply rewrite conditions in my htaccess file to all pages contained within a specific directory on my website, but not the directory index itself.
Ultimately, I'm trying to remove .php file extension from pages within a specific directory.
What I currently have now:
https://www.example.com/directory/page-1.php
End result I'm trying to achieve:
https://www.example.com/directory/page-1
Additionally, if a user attempts to visit the .php version of the page, it 301 redirects to the new version without the .php file extension.
Example matches:
https://www.example.com/directory/page-1.php
https://www.example.com/directory/page-2.php
Should not match:
https://www.example.com/directory/
Here's what I have so far:
RewriteCond %{REQUEST_URI} \/directory\/[^\s]+$
How should the RewriteRule be written?
The expression that might help us to find a RewriteRule can look like:
^https?:\/\/(www\.)?example\.com\/directory\/[^\s]+\.php$
which would fail our undesired URLs, and pass the desired ones.
Demo
Our RewriteRule might likely look like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} (.*\/directory\/)([^\s]+)\.php [NC]
RewriteRule (.*directory\/)([^\s]+)\.php $1$2 [L,R=301]
</IfModule>
Demo
RewriteRule Test
You can test your RewriteRules in htaccess.madewithlove.be.
RegEx Circuit
jex.im visualizes regular expressions:
We might also want to clear our browser cache, every time that we would change our htaccess file.
You can use the following rule in htaccess in your subfolder create one if it doesn't already exist :
RewriteEngine on
#rule for /subfolder/htaccess
#redirect /subfolder/file.php to /file
#The condition bellow prevents infinite loop/Too many redirects error
RewriteCond %{ENV_REDIRECT_STATUS} ^$
RewriteRule ^(.+)\.php$ /subfolder/$1 [L,R]
#internally map /subfolder/file to /subfolder/file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ /subfolder/$1.php [L]
If you want to use your root htaccess file instead , then add the following contents:
RewriteEngine on
#rule for root/.htaccess
#redirect /subfolder/file.php to /file
#The condition bellow prevents infinite loop/Too many redirects error
RewriteCond %{ENV_REDIRECT_STATUS} ^$
RewriteRule ^subfolder/(.+)\.php$ /subfolder/$1 [L,R]
#internally map /subfolder/file to /subfolder/file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^subfolder/(.+)/?$ /subfolder/$1.php [L]

htaccess doesn't work as expected

I have an htaccess rewrite URL as below:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.mywebsite.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^my-page\.html$ /my-page.php [L]
RewriteRule ^my-page/([^/]*)\.html$ /level1.php?num=$1 [L]
RewriteRule ^my-page/([^/]*)/([^/]*)\.html$ /level2.php?level1=$1&level2=$2 [L]
RewriteRule ^([^/]*)\.html$ /level3.php?level3=$1 [L]
These rules above rewrite URLs from mywebsite.com/my-page.php to mywebsite.com/my-page.html.
Now, what I want to achieve is mywebsite.com/my-page/ to be redirected to mywebsite.com/my-page.php (which in turn rewrites to mywebsite.com/my-page.html).
What I have tried, I created a directory "my-page" and tried to redirect requests from mywebsite.com/my-page/ to /my-page.html.
I don't know what went wrong. I can see in the network tab that a request is made to /my-page/ and gets rewritten to mywebsite.com/my-page.htmlmy-page/, which gives a 302 Status ☹
Please help! Thank you.
You can try use RedirectMatch to achieve this.
Redirect to my-page.php:
RedirectMatch 301 ^/my-page/ http://mywebsite.com/my-page.php
or straight away to my-page.html if this is your goal:
RedirectMatch 301 ^/my-page/ http://mywebsite.com/my-page.html
or, what will be best - change the code responsible for mywebsite.com/my-page.htmlmy-page/, but I can't see it in question you have asked :)
Please give the following a try. Brief descriptions are found in the comments for each section.
RewriteEngine On
# Trim www.
RewriteCond %{HTTP_HOST} ^www\.mywebsite\.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]
RewriteBase /
# Redirect /my-page[/] to /my-page.html
# >> Note: change 302 to 301 to make permanent
RewriteRule ^my-page/?$ my-page.html [R=302,L]
# Allow existing files and directories
# Recommended to comment out the first line
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite *.html to respective page
RewriteRule ^my-page.html$ my-page.php [L]
RewriteRule ^my-page/([^/]*).html$ level1.php?num=$1 [L]
RewriteRule ^my-page/([^/]*)/([^/]*).html$ level2.php?level1=$1&level2=$2 [L]
RewriteRule ^([^/]*).html$ level3.php?level3=$1 [L]
The important part here is that you do the required redirect before any other rewrites (except the www. removal).
Also, you previously had the two conditions which stated that if the request was not for a file or directory, then proceed with the next rule, but that wouldn't have accounted for the last two rules. As such, this version tells Apache to stop everything if the request is for an existing file or directory. I would recommend, for security purposes, that you comment out the line that checks for existing directories.

.htaccess mod rewrite help needed

I have written this little piece of code. I am very new to this so i am not sure it is all correct. but basically it lets me access urls with the php extension. When people get on the site they are being redirected from the geo ip page to the correct language which like looks like this
main.php?lang=uk or nl or en or eu etc.
right now i can also use it like this
main/?lang=uk or nl or en or eu etc.
I would like to be able to to also remove the variable in the url ?lang=uk.
How would i do this. My .htaccess code is below
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
DirectorySlash On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]
# remove trailing slash
RewriteRule ^(.*)\/(\?.*)?$ $1$2 [R=301,L]
RewriteRule ^([\w\/-]+)(\?.*)?$ $1.php$2 [L,T=application/x-httpd-php]
</IfModule>
Thanks too anyone willing to help.
The first argument of RewriteRule does match anything after the domain name and prefix* and before any query string if that exists. In http://localhost/this/is/my/test?lang=123 with a .htaccess file in the this/is/ directory it would match my/test. To match a query string, you have to use the %{QUERY_STRING} variable.
If the second argument (the rewritten url) of RewriteRule does not contain a query string, it will automatically append the query string of the original url to the new url.
In the code below I use %{THE_REQUEST}. This is the string that is used to make the request for a page. It is in the form of GET /my/resource?query=string HTTP/1.1. It does not change when rewriting things, which makes it useful to prevent infinite loops.
In your php file make sure that the language is read from a cookie instead of a get variable, then do the following:
#Set cookie for language
RewriteCond %{QUERY_STRING} ^(.*?)&?lang=([^&]+)&?(.*?)$
RewriteRule ^ %{REQUEST_URI}?%1&%3 [CO=lang:%2:127.0.0.1:1:/:0:1,R,L]
#Remove potential prefix or suffix & from query string
RewriteCond %{QUERY_STRING} ^&(.*?)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*?)&$
RewriteRule ^ %{REQUEST_URI}?%1 [R,L]
#External requests with \.php should be without that.
RewriteCond %{THE_REQUEST} \.php
RewriteRule ^(.*)\.php$ $1 [R=301,L]
#Try to load php page if resource does not alreay have an extension
RewriteCond %{REQUEST_URI} !\.[a-z]+$
RewriteRule ^(.*)$ $1.php [L]

Remove .php from example.com/test.php/foo/bar

I'm looking for a way to simply remove ".php" from a url while ignoring everything after the .php
So example.com/test.php/foo/bar would become example.com/test/foo/bar
and then in the PHP template I can search for and utilize foo or bar as I please. Everything I've found to remove .php interferes with the variables at the end.
UPDATE: I've found some success by removing .php from the file name and then using ForceType. Although It'd still be nice if I could keep the .php extension so my Code Editor knows how to highlight the syntax :)
<FilesMatch "^test$">
ForceType application/x-httpd-php5
</FilesMatch>
Update 2
Here's a RewriteRule that I've tried using to some success, but when I add a trailing slash and some content after, it results in a 500 internal server error
RewriteEngine On
RewriteBase /
# remove .php; use THE_REQUEST to prevent infinite loops
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
# remove index
RewriteRule (.*)/index$ $1/ [R=301]
# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]
# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]
Your last block is almost there. However you need a bigger assortment of RewriteConds to make it work with an optional PATH_INFO.
Namely you need to match the word characters from the REQUEST_FILENAME/_URI first, and then test for existence of a like-named .php script:
RewriteCond %{REQUEST_URI} ^/(w+)/
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(\w+)/(.+)$ $1.php/$2 [L]
The last RewriteRule depends on existing trailing vars. Add one of the generic rule blocks for plain http://example.com/test requests without PATH_INFO. Note that this specific set will work with xyz.php scripts in the webroot only.
Please try to recheck this:
RewriteCond %{REQUEST_URI} ^/([a-z0-9-_]+)/([a-z0-9-_]+)/([a-z0-9-_]+)/?$
RewriteRule ^(.*) ^/%1.php/%2/%3

Issue with mod_rewrite when accessing directory

My code:
RewriteEngine on
RewriteBase /
RewriteRule ^article/([a-z]+)/?$ index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ index.php?page=$1 [L]
I am using WAMP and had setup a Virtual Host.
In my index.php, there is code to get page passed and checks if it exists(in database). If not, display an error message. It works fine.
Eg: http://mysite/contactus/
But it will not work if I use a a directory name as page_name in the URL. Eg: http://mysite/images/. This will display page not found error (ie. checks database and no page found, so display "not found"). But it will not display images,css(linked file) in the page. Also, it shows http://mysite/images/?page=images in addressbar.
Like that, if I goto js folder which is used to store javascript files, above problem occurs. So, problem is caused if any subdirectory's name is passed as pagename.
How to solve this ?
When http://mysite/images/ is supplied, mod_rewrite is redirecting to http://mysite/images/index.php?page=images instead of http://mysite/index.php?page=images
Edit
Please tell me how to block hotlinking of files and directory, and redirect back to index page or send some browser header error ?
I tried this:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*) http://%{HTTP_HOST} [R,L]
RewriteRule ^article/([a-z]+)/?$ /index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ /index.php?page=$1 [L]
Edit
New code(semi-working):
RewriteEngine on
RewriteBase /
# remove trailing slash ONLY if it is not an existing folder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1/ [R,L]
RewriteRule ^article/([a-z]+)/?$ http://%{HTTP_HOST}/index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ http://%{HTTP_HOST}/index.php?page=$1 [L]
This code will clear the problem with not displaying pics and css when a directory name is mentioned. But whatever pagename i specify eg:http://mysite/contactus, it will goto URL: http://mysite/index.php?page=contactus. Even if I use a directory name eg: http://mysite/js, it will goto: http://mysite/index.php?page=js
I am very confused.
RewriteEngine on
RewriteBase /
RewriteRule ^article/([a-z]+)/?$ index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/*$ /index.php?page=$1 [L]
you have to put the slash in front.
Edit: changed the ? to *
My understanding is that your script is for documents only, not images or other resources.
Then you should ignore them right away. Try adding this line right after RewriteBase like this :
RewriteEngine on
RewriteBase /rewrite/
RewriteRule ^/(images|js)/(.*)$ - [L]
RewriteRule ^article/([a-z]+)/?$ index.php?page=article&name=$1 [L]
RewriteRule ^([a-z]+)/?$ index.php?page=$1 [L]
Then these subdirectories would be served right away, thus bypassing the next RewriteRule set.
For the problem with the directories I usually force a slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+[^/])$ $1/ [R]

Categories