This can be achieved by a trick with Apache httpd using an Inline Login flow.
Basically when a user tries to access a protected resource, then httpd will show him the login form (configured as error document) within the same page without redirecting the user to login page.
Basic inline example
AuthFormProvider file
ErrorDocument 401 "/login.shtml"
AuthUserFile "conf/passwd"
AuthType form
AuthName realm
AuthFormLoginRequiredLocation "http://example.com/login.html"
Session On
SessionCookieName session path=/
Example inline login form
<form method="POST" action="">
Username: <input type="text" name="httpd_username" value="" />
Password: <input type="password" name="httpd_password" value="" />
<input type="submit" name="login" value="Login" />
</form>
refer - https://httpd.apache.org/docs/2.4/mod/mod_auth_form.html (Inline Login)
This will help to preserve the incoming URI and when user clicks the login button, if the authentication is successful then the user will be granted to access the resource.
So this will avoid page redirect to login page and in turn this preserves the page state & contents.