Home Ask Login Register

Developers Planet

Your answer is one click away!

Blackpool Towr February 2016

.htaccess won't rewrite correctly

I'm having some issues with my .htaccess file, stored at the root level of my website.

I want to rewrite the following

  1. mysite.com executes mysite.com/index.php?lang=en but rewrites the URL to mysite.com/en/
  2. mysite.com/en (without the trailing slash) does the same as above
  3. mysite.com/en/blog/page executes mysite.com/blog/page?lang=en

In a nutshell, add the language to the URL, opening index.php with either .com, .com/en or .com/en/, and strip the file extension

Here is the complete file for reference:

RewriteEngine on

# Redirect to domain without www.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* http://%1%{REQUEST_URI} [R=301,L]
# Same for HTTPS:
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule .* https://%1%{REQUEST_URI} [R=301,L]

# Stop hotlinking.
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} ^https?://([^/]+)/ [NC]
RewriteCond %1#%{HTTP_HOST} !^(.+)#\1$
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [NC,F,L]

# Prevent directory listings
Options All -Indexes

# Request language from URL
# empty url -> redirect to en/
RewriteCond %{QUERY_STRING} !lang=(en|de)
RewriteRule ^$ en/ [R=301,L]

# now all urls have en/ de/ -> parse them
RewriteRule ^(en|de)/(.*)$  $2?lang=$1&%{query_STRING} [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

For full disclosure, it has all been taken from a variety of Google results, and I appreciate it could perhaps be done better.

As it stands, mysite.com gives me

The requested URL /home/towrafvk/public_html/en/.php was not found on this server.

mysite.com/en gives me

The requested URL /en.php was not found on this server.

mysite.com/en/ AND mysite.com/en/blog/page both work as intended

I know the issue is in the third-to-l

Answers


Croises February 2016

RewriteEngine on

# Redirect to domain http(s) without www.
RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://%1%{REQUEST_URI} [NE,L,R=301]

# Stop hotlinking.
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} ^https?://([^/]+)/ [NC]
RewriteCond %1#%{HTTP_HOST} !^(.+)#\1$
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [NC,F,L]

# Prevent directory listings
Options All -Indexes

# Request language from URL
# empty url -> redirect to en/
RewriteCond %{QUERY_STRING} !lang=(en|de)
RewriteRule ^$ en/ [R=301,L]

# now all urls have en/ de/ -> parse them
RewriteRule ^(en|de)/(.*)$  $2?lang=$1 [L,QSA]

# Use .php file only if not exist without and exist with .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(.+)/?$ $1.php [L]

Post Status

Asked in February 2016
Viewed 1,859 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life