htaccess – RewriteCond %{HTTPS} !=on is not working even though RewriteCond %{SERVER_PORT} !^443$ works

My understanding is that RewriteCond %{HTTPS} !=on will match all URLs that are not HTTPS.

Yes, that is correct. In this context, HTTPS is a server variable, set by Apache based on the request hitting your server.

But upon testing, I find RewriteCond %{HTTPS} !=on is matching both HTTP and HTTPS URLs.

That’s not possible if the SSL cert is installed directly on your application server. However, if you are using an SSL proxy, whereby the SSL is handled by a front-end proxy and the connection from the SSL proxy to your application server is plain-old HTTP (such is the case with Cloudflare’s free Flexible SSL option) then this will indeed appear to be the case because your server is only serving traffic over HTTP.

However, RewriteCond %{SERVER_PORT} !^443$ is matching non HTTPS URLs correctly?

However, this contradicts the above! If this works then so should the check against HTTPS. This would seem to suggest you are perhaps seeing a cached response above?

htaccess – 301 redirect with regex: how to match any file at top domain level (not in a subdirectory)?

A RewriteRule only matches the file path. You can’t include part of the domain name in the rewrite rule because the rule will never match it.

To match something at the start of the path, use the “starts with” regex operator: ^.

To ensure that you are not matching anything in sub-directories, make sure not to match any slashes in your pattern. (^/)+ instead of .* means “at least one character that isn’t a slash” rather than “zero or more characters”. The caret inside the square bracket is the negation of a character set.

Your final rewrite rule should be:

RewriteRule ^/?((^/)+.dmg)$ /downloads/$1 (R=301,L,NC)
  • ^/?: starts with an optional slash
  • (...): parenthesis around the file name (including “.dmg”) which becomes $1 in the replacement
  • (^/)+: At least one character other than slashes
  • .: A literal period
  • $: “ends with”, ensure there is nothing after the file name

Make sure this rewrite rule is at the top of your .htaccess file so that it takes precedence over other rewrite rules including the default wordpress rules.

.htaccess how to redirect the contents of a directory to a subdirectory

RewriteRule ^/folder(.*)$ /folder/subfolder/$1 (R=301,NC,L)

As just mentioned in this other answer… in per-directory .htaccess files the RewriteRule pattern matches the URL-path less the directory-prefix, so the URL-path that is matched does not start with a slash. So, the pattern should be more like: ^folder(.*)$

Unless you have a requirement to use the root .htaccess file, I would create a .htaccess file in the directory you are redirecting from instead. So, in the /folder/.htaccess file (not the document root), try the following:

RewriteEngine On
RewriteBase /folder

RewriteCond %{REQUEST_URI} !^/folder/subfolder
RewriteCond %{REQUEST_URI} !^/folder/exclude-file1.html$
RewriteCond %{REQUEST_URI} !^/folder/exclude-file2.html$
RewriteCond %{REQUEST_URI} !^/folder/exclude-dir
RewriteRule (.*) subfolder/$1 (R=302,L)

The NC flag is not required here.

The first RewriteCond directive is to prevent a redirect loop, since we are redirecting to a subfolder of the folder we are redirecting from!

I’ve also used a 302 (temporary) redirect. When you are sure it’s working OK, change to a 301 (permanent) – if that is the intention. 301s are cached by the browser so can make testing problematic.

.htaccess remove string at the end of url

Suppose I have urls like these:

/toys/id-2005200520056-what-ever-toy-name

I would like to only keep the id part:

/toys/id-2005200520056

The id always has 13 digits.

This is what I tried but it’s not working.

RewriteRule ^(id-(0-9){13}) $1 (L)

Can someone please help me out? Thanks.

themes – .htaccess edits – WordPress Development Stack Exchange

WordPress newbie here, apologies if things don’t make sense.

I bought a premium theme and uploaded/installed it to WordPress. Surely enough, after doing so, I found out that I was supposed to add the following values to .htaccess:

php_value post_max_size 64M
php_value upload_max_filesize 64M
php_value max_file_uploads 128M
php_value max_input_vars 5000

The authors are very adamant to do this BEFORE installing and activating the theme, but that’s already too late in my case.

What’s the appropriate course of action here, deactivate and delete the theme in question in order to add those lines to .htaccess?

Add an access right in an .htaccess file

How to add read and write rights to an .htacc file because I know a serious problem on my sharing site

htaccess – how to make rewrite any directory that does not have an index.php

you know usually when someone goes to a page with no index.php it displays all the list of file there(which i don’t want to happen), how can i create a custom page for that instead of showing all the files(using htaccess) for example:

ErrorDocument noindex /noindex/index.html

OR

RewriteRule noindex /noindex/index.html

htaccess – How to stop access of a PHP file from other sites

this example is for image even you can do same for any file type
You could make that folder not accessible from the web (e.g. place the folder outside htdocs or add .htaccess rules ).

Create a PHP script which handles all requests to the private images. This script would have to do the following:

-check if the user is authenticated
-check if the user is authorized to view the requested image open the image and print it to the browser
(you need to set correct http headers to make sure the content is treated as an image)

Demo

getimage.php

  if (LoggedInUserCanAccessThisFile())//this is optional user define function as requirement if you want that only login user can see image then with the help of your session variables or cookies you can return this function true or false 
    {
    $file = 'privatedir/image.jpg';
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit();
    }

home.php/otherpage.php

<img src="https://webmasters.stackexchange.com/getimage.php" />

(you can use src=”https://webmasters.stackexchange.com/getimage.php?userid=123″ and get into getimage.php and check is this user logged in or not for showing image)

(also you can use src=”https://webmasters.stackexchange.com/getimage.php?userid=123&imgfilename=image3.jpg” for dynamic images code and get into getimage.php as

$file = 'privatedir/'.$_GET("imgfilename");

)

how to stop htaccess rewrite rule from rewriting all urls

i am having a mod rewrite problem and i am new to htaccess not because i tried to do a mod_rewrite and link i try to open assumes that i am in profile.php
heres my code

FOR HTACCESS

 ErrorDocument 404 /404,/
RewriteEngine On
RewriteRule ^((a-zA-Z-9_-)+)$ profile.php?username=$1
RewriteRule ^((a-zA-Z-9_-)+)/$ profile.php?username=$1

I just wanted localhost/qwerty to display profile.php anything else should show the normal page and if it does not exists it shows a 404 error

FOR PROFILE.PHP

    <!DOCTYPE html>
<html>
<head> 
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="style.css"/> <title class="notranslate">Ny rocks</title>
    <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        profile.php             
    </body>
</html>
     <?php
    $conn=mysqli_connect("localhost","root","","databasename");
    if(!$conn){
        
        die("connection failed". mysqli_connect_error());
    }
           if(!isset($_GET('username'))){
                    header("location:./login,/?error=true");
                }else{   
         $username = $_GET('username');
      $quer="SELECT * FROM users WHERE username='$username'";
    $result=$conn->query($quer);
    if(!$row=$result->fetch_assoc()){
       echo 'user does not exist';
    }else{
        echo 'user exists';
    }
    
    } ?>

NOW MY FILE TREE

                                               htdocs(xampp)
                                                   |
 =======================================================================================
 |         |          |              |                       |                         |
login,    404,     style.css      profile.php              index.php               .htacccess

Now the problem is that none of the style sheets (or the javascript files) load , all the pages on http://localhost are now assumed to be profile.php, and in profile.php $_get(‘username’) displays ‘profile.php’ instead of ‘user123’
Just to be clear i want it that if http://localhost/login, is the url then login, loads(i even added a comma at the end of login to make the .htaccess not to look at login as a username, but that doesn’t work),

i have cleared my cache so many time but it doesn’t work

Even when i go to http://localhost/ it shows profile.php

Why is Apache reading .htaccess files even though they are disabled?

According to Apache documentation, setting the “AllowOverride” and “AllowOverrideList” options to “None”, will completely ingnore .htaccess files. Not even attempt to read them from the filesystem.

I have both of those options set to none but Apache still reads the .htaccess files. I know this because if I put an .htaccess file in with some valid directives it throws a 500 error. Commenting out the directives (essentially an empty .htacces file) the 500 error is not thrown. So obviously Apache is still reading the .htacces files.

Apache2 error log (sanitized for public consumption):
(Thu Jul 30 23:36:35.393831 2020) (core:alert) (pid 60903) (client d.d.d.d:10554) /var/www/example/.htaccess: Require not allowed here, referer: http://example.net/

The question is why? What am I missing? How to make it behave according to the documentation? i.e. not even attempt to read the .htaccess files.

Reference:
https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride

When this directive is set to None and AllowOverrideList is set to
None, .htaccess files are completely ignored. In this case, the server
will not even attempt to read .htaccess files in the filesystem.